如何在Android外部的应用程序外警报警报消息?

时间:2012-05-22 12:34:16

标签: android notifications alarmmanager android-notifications android-alarms

我正在尝试使用此代码弹出警报消息。它在启动或打开应用程序时工作,但它不会在应用程序外部显示任何弹出消息。 我很困惑,我不知道我做错了什么。

String alarmtime = cur.getString(cur.getColumnIndex(DBDATA.LG_ALARMTIME));
//Reminder
String[] timesplit = alarmtime.split(":"); 
int hour = Integer.parseInt(timesplit[0]);
int minute = Integer.parseInt(timesplit[1]);
System.out.println(hour);
System.out.println(minute); 

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ShortTimeEntryReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); 

Calendar alarm = new GregorianCalendar();
alarm.setTimeInMillis(System.currentTimeMillis());
alarm.set(Calendar.HOUR_OF_DAY, hour);
alarm.set(Calendar.MINUTE, minute); 
alarm.set(Calendar.SECOND, 0);  
System.out.println(System.currentTimeMillis());
System.out.println(alarm.getTimeInMillis());
if (System.currentTimeMillis() > alarm.getTimeInMillis()){
    alarm.setTimeInMillis(alarm.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
    alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);
}
else
{
    alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);                 
}

我需要在应用程序之外弹出警报消息(即),就像警报一样。 谢谢你的帮助,

1 个答案:

答案 0 :(得分:2)

您可能需要BroadcastReceiver

正如您可以在这个问题中读到的那样:BroadcastReceiver not receiving an alarm's broadcast

你必须建立这样的意图:

Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, "CHECK_ALARM_CODE", alarmIntent, 0);

并收到这样的警报:

    public class AlarmReceiver extends BroadcastReceiver{
      @Override
      public void onReceive(Context context, Intent intent) {
         Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
         Log.d("OK", "AlarmReceiver.onReceive");
      }
}

不要忘记在清单文件中注册广播。