问题
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