应用程序未运行时如何通知用户报警?

时间:2018-03-16 12:08:20

标签: android android-studio alarmmanager android-alarms

我有一个应用,我想在特定的日期和时间设置闹钟。比如说3月16日下午5点。我希望这个闹钟安排为非重复闹钟。

现在警报正在设置并正常工作。但它只在App工作或在后台工作时才有效。但当应用程序被强制关闭时,它无法正常工作。

这是我正在做的事情:

 public void startAlert() {  
        EditText text = (EditText) findViewById(R.id.time);  
        int i = Integer.parseInt(text.getText().toString());  
        Intent intent = new Intent(this, MyBroadcastReceiver.class);  
        PendingIntent pendingIntent = PendingIntent.getBroadcast(  
                                      this.getApplicationContext(), 234324243, intent, 0);  
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);  
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  
                                      + (i * 1000), pendingIntent);  
        Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();  
    } 

这段代码只是为了演示。问题是,当我从app任务管理器清除我的应用程序时,alaram不是alaram。

我知道有一些问题,因为android os取消注册预定警报,重启时也可能出现问题。

当时我真的不关心重启,但是当应用程序被强制关闭时,警报应该可以正常工作。如果它不适用于Android那么其他应用程序如何做这个???

请分享您对此的看法?告诉我如何在一天中的特定时间通知我的用户的任何其他解决方案,即使我的应用程序甚至不在后台?请帮忙

2 个答案:

答案 0 :(得分:0)

用于设置警报。请在代码

下使用
if (SDK_INT < Build.VERSION_CODES.KITKAT) {
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  
                                  + (i * 1000), pendingIntent);
}
else if (Build.VERSION_CODES.KITKAT <= SDK_INT  && SDK_INT < Build.VERSION_CODES.M) {
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  
                                  + (i * 1000), pendingIntent);
}
else if (SDK_INT >= Build.VERSION_CODES.M) {
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  
                                  + (i * 1000), pendingIntent);
}

答案 1 :(得分:0)

来自AlarmManager

AlarmManager提供对系统警报服务的访问。这些允许您安排应用程序在将来的某个时间运行。当警报响起时,系统会广播已为其注册的Intent,如果目标应用程序尚未运行,则会自动启动它。设备处于睡眠状态时会保留已注册的警报(如果设备在此期间关闭,则可以选择将设备唤醒),但如果设备关闭并重新启动则会清除设备