I am using alarm manger to set broadcast on 2am every day. Alarm manager working fine in normal scenarios but it failing in below scenario.
Can some one help me with this scenario
//Alarm manager
//timeToTwoAm is calculate time to 2AM from current time
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,timeToTwoAm,
AlarmManager.INTERVAL_DAY, alarmIntent);
Your alarms will not be persisted. After a reboot all your registered alarms are removed.
2 solutions would be helpful:
1. Register a BOOT_COMPLETED broadcast receiver:
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".notification.alarm.OnBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
And in your OnBootReceiver simply register your alarms at AlarmManager again.
2. Use JobScheduler-API (>= API 21) or GcmNetworkManager (PlayServices)
Depending on your use case it would also be possible to use the new GcmNetworkMaanger, which allows persisting a Job during reboot.
Add Service to your Manifest:
<service
android:name=".LoadWeatherService"
android:exported="true" android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>
In your service declare the things to do:
public class LoadWeatherService extends GcmTaskService {
public void onInitializeTasks() {
super.onInitializeTasks();
// Reregister your Job after update of Google Play Services
}
@Override
public int onRunTask(TaskParams taskParams) {
// Do your stuff
return GcmNetworkManager.RESULT_SUCCESS;
}
}
Subscribe your Job
String tag = "myperiodicTask";
PeriodicTask periodicTask = new PeriodicTask.Builder().setService(LoadWeatherService.class)
.setRequiredNetwork(Task.NETWORK_STATE_CONNECTED).setPeriod(60L).setFlex(10L)
.setTag(tag).setPersisted(true).build();
GcmNetworkManager.getInstance(this).schedule(periodicTask);
Please notice: This is only a sample from my app, you have to adjust this regarding your needs.
Further Reading about GcmNetworkManager: https://developers.google.com/cloud-messaging/network-manager
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.