手机关闭时的AlarmManager - ANDROID

时间:2012-09-02 05:22:23

标签: android alarmmanager android-pendingintent android-alarms

我正在做一个报警系统,但是当手机关机时我遇到了问题..闹钟不起作用..

我按照以下方式设置了警报:

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

}

当手机开机时闹钟正常工作..

我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:7)

是的,问题是当手机重启时你的应用程序没有运行。您需要注册一个可以接收BOOT_COMPLETED消息的BroadcastReceiver,以便在手机重新启动时收到消息。然后在BroadcastReceiver中,您可以重新安排这些警报或其他任何内容。但我不认为在手机关闭时你可以做任何关于触发警报的事情......(例如打开手机)

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

答案 1 :(得分:3)

当手机关闭并重新启动时,警报会被清除,但您可以使用可以接收BOOT_COMPLETED的BroadcastReceiver启动警报

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>

爪哇:

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

  }

}