【问题标题】:AlarmManager keeps bringing activity to foregroundAlarmManager 不断将活动带到前台
【发布时间】:2016-05-04 08:38:34
【问题描述】:

我正在尝试编写将在后台运行并调用服务器 API 的代码。谷歌搜索导致我使用 AlarmManager,这是我的代码:

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            int interval = 4000;

            Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

但这里的问题是,当我的应用程序在前台(当前在 android 主菜单或其他应用程序上)时,只要警报触发,它就会将我的活动发送到前台。

有谁知道为什么会发生这种情况以及如何避免这种情况?我有一个由 AlarmReceiver 类启动的服务,我希望它在后台运行。

AlarmReceiver.class:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent(context, LogService.class);
    i.putExtra("param1", "index.html");
    i.putExtra("param2",
        "http://www.vogella.com/index.html");
    context.startService(i);
}

}

LogService.class

public class LogService extends IntentService{

    public LogService() {
        super("LogService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String param1 = intent.getStringExtra("param1");
        String param2 = intent.getStringExtra("param2");

        Log.i("Hello from logservice!", "!!! -- " + param1 + " - " + param2);
    }

}

在清单中添加了一些东西:

<receiver android:name="com.example.app.alarm.AlarmReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

<service android:name="com.example.app.alarm.LogService" >
</service>

提前致谢!

【问题讨论】:

  • 能发一下AlarmReceiver的代码吗?
  • 您好,已编辑帖子。包括 AlarmReceiver 和 LogService 类。
  • 您是否在清单文件中声明了服务?
  • 您好,帖子已编辑。添加清单中的内容。

标签: android android-activity broadcastreceiver alarmmanager background-process


【解决方案1】:

阅读后,我发现从 API 19 开始,所有重复的警报都是不准确的。在了解了这一点后,我尝试使用 setRepeating 功能。我不知道为什么它的行为不同,但现在一切都按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多