Alarm is not working in android when the device is off and on again

只愿长相守 提交于 2019-12-23 12:06:16

问题


I have set the alarm to remind me in android it is working when the device is on. But when i switch off the device and again on that reminder alarm is not working. Can you guys please suggest me how can solve this problem?

My code looks like this,

Intent myIntent = new Intent(getApplicationContext(), serviceclass.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
    CONST+id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Calendar calender = Calendar.getInstance();
calender.setTimeInMillis(System.currentTimeMillis());
calender.set(Calendar.HOUR_OF_DAY, hours);
calender.set(Calendar.MINUTE, ireminder.getMin());
calender.set(Calendar.SECOND, 0);
calender.set(Calendar.MILLISECOND, 0);  
calender.set(Calendar.DAY_OF_WEEK, day);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,  

calender.getTimeInMillis(), 7 * AlarmManager.INTERVAL_DAY, pendingIntent);                

回答1:


Alarms will be cleared on reboot.

What you can do is

  1. persist alarm information in a db table
  2. register for the REBOOT_COMPLETED-Event
  3. On reboot, start a background thread the re-registers alarm. Make sure that you compute the alarm times correctly.

See API: "Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted." - http://developer.android.com/reference/android/app/AlarmManager.html




回答2:


Create a class OnBootReceiver

public class OnBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        mgr.setRepeating(AlarmManager.RTC_WAKEUP,
        SystemClock.currentThreadTimeMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                    pi); 

    }

}

inside manifest

<receiver android:name=".OnBootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

inside your activity

sendBroadcast(new Intent(this, OnBootReceiver.class));


来源:https://stackoverflow.com/questions/5616769/alarm-is-not-working-in-android-when-the-device-is-off-and-on-again

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