一段时间后,警报管理器和通知无法正常工作

时间:2015-05-18 06:50:58

标签: android service notifications broadcastreceiver alarmmanager

我已经设置了一个警报管理器,当警报发出时,我已经定义了一个通知,显示在接收者的onReceive中。

我已经在我的活动停止时定义了警报管理器代码,因此它仅在应用程序关闭后才开始运行

这是onStop方法中的代码

public void onStop() {

    super.onStop();
    // alrm manager called in on stop so that timer starts after we finish the app
    Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis()+NOTIFICATIONTIME,NOTIFICATIONTIME, pendingIntent);
}

我已取消先前在onresume上发出的警报,以便在我参与活动时听不到通知

public void onResume() {

    super.onResume();

    //this helps to cancel all the previously made alarms so that no notification in between game
    cancelAlarm(getApplicationContext());
}
public void cancelAlarm(Context context) {

    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}

这是触发通知的闹钟接收器

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // When our Alaram time is triggered , this method will be excuted (onReceive)
        // We're invoking a service in this method which shows Notification to the User

        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Uri notificationbark = Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.notificationbark);
        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon).setContentTitle("Name").setContentText("text").setSound(notificationbark).setAutoCancel(true).setWhen(when).setContentIntent(pendingIntent);
        notificationManager.notify(0, mNotifyBuilder.build());
    }
}

通知显示了一天,但现在却没有。

0 个答案:

没有答案