AlarmManager当手机处于关机状态 - ANDROID(AlarmManager when

2019-06-27 16:53发布

我在做一个报警系统,但我有一个问题,当手机处于关闭状态。该报警器不工作..

我将de报警如下:

    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);

}

当手机打开时,报警工程确定..

我能做什么?

谢谢!

Answer 1:

是的,问题是你的应用程序没有运行在手机重新启动时。 你需要注册,以便接收当消息在手机重启可以接收BOOT_COMPLETED消息的广播接收器。 然后在广播接收器,你可以重新安排这些警报或什么的。 但我不认为有什么可以做使你触发报警时,手机处于关闭状态。(例如,使得在手机上转)

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


Answer 2:

当手机关闭警报被清除并重新启动,但可以使用广播接收器,可以接收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);         
    }  

  }

}



文章来源: AlarmManager when the phone is turned off - ANDROID