【问题标题】:Android IntentService runs only ONCE after phone is restarted. Why?Android IntentService 只在手机重启后运行一次。为什么?
【发布时间】:2015-02-08 19:42:49
【问题描述】:

背景和问题

我在stackoverflow上查看了几十个教程、示例和问题,这些都与手机关机后服务未注册的问题有关。

我的问题几乎相似,但略有不同:我使用IntentService(我需要从外部数据库收集数据并将其显示为通知)并且服务每 30 秒运行一次,直到我切换手机关机。

有趣的部分

奇怪的行为来了!我把手机转回来,IntentService 只注册了一次。启动后,我只收到一次通知(在示例中,为了简单起见,我只使用日志),然后再也不会收到通知。

部分 Activity 代码(我可以在其中设置服务)

private void setRecurringAlarm(Context context) {

        AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, BackgroundDataServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 30);   

        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
        cal.getTimeInMillis(), 30*1000, pending);   

    }

IntentService

public class BackgroundDataService extends IntentService {

....
@Override
    protected void onHandleIntent(Intent intent) {

      Log.i("BACKGROUNDDATASERVICE STATUS", "running");

    }
}

广播接收器

public class BackgroundDataServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent dailyUpdater = new Intent(context, BackgroundDataService.class);
        context.startService(dailyUpdater);

    }
}

清单

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 <application
...
  <service android:name="com.example.blgui3.BackgroundDataService" >
        </service>

        <receiver android:name="com.example.blgui3.BackgroundDataServiceReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

...
</application>

据我所知,我的 service 是否需要执行后台任务,例如使用AsyncTask从外部数据库获取数据,那么推荐使用IntentService。即使我在启动后启动应用程序,该服务仍然只运行一次,因此它根本没有注册 BOOT_COMPLETE 操作。在为此挣扎了几个小时之后,我完全不知道我哪里出错了。

【问题讨论】:

    标签: android broadcastreceiver intentservice android-intentservice


    【解决方案1】:

    该服务在使用BOOT_COMPLETED 启动后启动,但不会启动任何活动,似乎只有活动设置了警报。

    【讨论】:

    • 我不想开始任何活动。该服务由 BroadcastReceiver 启动。那我应该在哪里设置闹钟呢?什么解释了服务被调用一次但不再被调用?
    • 广播接收器由BOOT_COMPLETED调用,而不是警报。系统仅广播一次该意图,因此您的接收器仅被触发一次。我建议当您收到BOOT_COMPLETED 时,您在广播接收器中设置闹钟。
    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多