Android service scheduled on AlarmManager not starting

久未见 提交于 2019-12-25 07:31:21

问题


I have a service (properly declared in the Manifest file) that upon onDestroy() schedules itself to start again one minute later via AlarmManager. However the service is not starting even though onDestroy() runs correctly. What could be wrong?

The scheduling code:

@Override
public void onDestroy() {

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent i) {
            c.startService(new Intent(c, MyService.class));
        }
    };

    registerReceiver(br, new IntentFilter("xxxx"));

    PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("xxxx"), 0);

    AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));

    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ONE_MINUTE, pi);

    Log.i("onDestroy", "Service scheduled.");

    unregisterReceiver(br);

    super.onDestroy();
}

The service declaration in the Manifest file:

<service
    android:name="com.xxxx.MyService"
    android:exported="true">
</service>

回答1:


First, your BroadcastReceiver is going away nanoseconds after the end of onDestroy(), making it useless. Please register your BroadcastReceiver in the manifest with a <receiver> element.

Second, a _WAKEUP alarm only keeps the device awake long enough to process an onReceive() in a BroadcastReceiver. You need to use a WakeLock to keep the device awake longer than that. Depending upon what you are doing, my WakefulIntentService may be of some use.

Third, you do not need to export your service, and by doing so, you are opening up potential security holes. I recommend removing android:exported="true".



来源:https://stackoverflow.com/questions/17073938/android-service-scheduled-on-alarmmanager-not-starting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!