再起動の場合に保留中のすべてのアラームを保存するためのテーブルがデータベースにあります。電話が再起動された場合、アラームをリセットするサービス クラスがあります。
private AppDatabase mDbHelper;
public class BootService extends Service {
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mDbHelper = new AppDatabase(this);
mDbHelper.open();
}
@Override
public void onStart(final Intent intent, final int startId) {
super.onStart(intent, startId);
LoadNotificationsFromDB();
}
private void LoadNotificationsFromDB() {
Cursor c = mDbHelper.getPendingNotifications();
if (c.moveToFirst()) {
do {
int id = c.getInt(AppDatabase.ID_COLUMN);
String date = c.getString(AppDatabase.DATE_COLUMN);
addNotification(id, date);
} while (c.moveToNext());
}
c.close();
}
private void addNotification(int id, String date) {
Intent intent = new Intent(BootService.this,
NotificationBroadcastReceiver.class);
PendingIntent mAlarmSender = PendingIntent.getBroadcast(
BootService.this, id, intent, 0);
long alarmDate = Long.valueOf(date);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, date, mAlarmSender);
}
}
次に、Receiver クラスを作成します。
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent mServiceIntent = new Intent();
mServiceIntent.setAction("<package name>.BootService");
ComponentName service = context.startService(mServiceIntent);
if (null == service) {
// something really wrong here
}
}
}
}
そして、次の行をManifest.xml
<receiver android:name=".BootReceiver" android:enabled="true">
<intent-filter>
<action android:name ="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />