AlarmManager when the phone is turned off - ANDROI

2019-02-09 16:28发布

I'm doing an alarm System but i've a problem when the phone is turned off.. The alarm doesn't work..

I'm setting de alarm as follows:

    public void doIntents(Context context, long milis, Tratam trat){
    cal=Calendar.getInstance();
    alarmManager = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);

    cal.setTimeInMillis(milis);
    Intent intent = new Intent(context, OnAlarmReceiver.class);


    pendingIntent = PendingIntent.getBroadcast(context, trat.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.RTC_WAKEUP,milis ,pendingIntent);

}

The Alarm works Ok when the phone is turned on..

What can I do?

Thank you!

2条回答
地球回转人心会变
2楼-- · 2019-02-09 17:10

Yea, the problem is your app isn't running when the phone restarts. You'll need to register a BroadcastReceiver that can receive the BOOT_COMPLETED message so it receives a message when the phone reboots. Then in the BroadcastReceiver you can either reschedule those alarms or whatever. But I don't think there's anything you can do about making your alarm trigger when the phone is off..(e.g. making the phone turn on)

<receiver android:name="MyBootReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="BootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>

        </intent-filter>
    </receiver>
查看更多
我想做一个坏孩纸
3楼-- · 2019-02-09 17:20

Alarms are cleared when the phone turned off and rebooted, but you can start your alarm using BroadcastReceiver that can receive the BOOT_COMPLETED

In Manifest.xml:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <application ...>
 <receiver android:name="com.example.receiver.AlarmMonitorReceiver"
              android:enabled="true"
              android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
</application>

Java:

public class AlarmMonitorReceiver extends BroadcastReceiver{
  public void onReceive(Context context,Intent intent) { 
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
      AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
      Intent intentAlarm = new Intent(context, ExampleReceiver.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intentAlarm, 0);
      Calendar time = Calendar.getInstance();
      time.setTimeInMillis(System.currentTimeMillis());
      time.add(Calendar.SECOND, 10);
      alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),10000,pendingIntent);         
    }  

  }

}

查看更多
登录 后发表回答