警报管理器多次重复通知[android]

时间:2016-12-17 11:12:30

标签: android notifications broadcastreceiver alarmmanager android-pendingintent

我正在尝试提醒药片。当我创建多个提醒时,我的应用程序会显示所有通知,但仅在上次设置时显示。它还执行更多次OnReceive()方法,我不明白为什么。我用相同的论点发现了许多问题,我用这些答案改变了我的代码,但没有解决我的问题。谢谢!

设备:华硕ZenPad S 8.0; Android:6.0.1;

这是我的代码:

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button:
            mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    mcurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
                    mcurrentTime.set(Calendar.MINUTE, selectedMinute);
                    setAlarm();

                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle(R.string.orario);
            mTimePicker.show();
            notificationAlarm = new NotificationAlarm(editText.getText().toString());
            getApplicationContext().registerReceiver(notificationAlarm, intentFilter); 
            break;
}}


 private void setAlarm(){
    int id = (int) System.currentTimeMillis();
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,id, intent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mcurrentTime.getTimeInMillis(),1000*60*5, pendingIntent);
    Log.d("Time", String.valueOf(mcurrentTime.getTimeInMillis()));

}



@Override
public void onResume(){
    super.onResume();
    final String SOME_ACTION = "com.example.mypackage.a2_pillsrem_WAKE";
    intent = new Intent(SOME_ACTION);
    intentFilter = new IntentFilter(SOME_ACTION);
}

这是BroadcastReceiver类:

public class NotificationAlarm extends BroadcastReceiver {
String s;
int mNotificationId;
Random r = new Random();
ArrayList<Integer> notify = new ArrayList<>();
public NotificationAlarm(String s){
    this.s=s;
}

public void onReceive(Context context, Intent intent) {
    //RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification);

    Notification.Builder mBuilder =
            new Notification.Builder(context)
                    .setSmallIcon(R.drawable.pill)
                    .setContentTitle(context.getString(R.string.titolo_notifica))
                    .setContentText(context.getString(R.string.descr_notifica)+" "+s)
                   // .setContent(remoteViews)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setVisibility(1);//1 è uguale a VISIBILITY_PUBLIC
                                        // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.html#VISIBILITY_PUBLIC

    //Random r = new Random();
    mNotificationId = r.nextInt(10000); //assegno un id casuale ad ogni notifica affinchè non siano sovrascritte
    Intent notificationIntent = new Intent(context,MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context,0,notificationIntent,0);
    mBuilder.setContentIntent(pendingIntent);
    Log.d("IDNOT",Integer.toString(mNotificationId));
    //Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr =
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
   // Builds the notification and issues it.
    mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}

2 个答案:

答案 0 :(得分:0)

您是否尝试使用var replaceHyphen = function (str) { return str.replace(/(\d)-|(-)-/g, '$1$2'); }; console.log(replaceHyphen('50-50')); console.log(replaceHyphen('50,00-')); console.log(replaceHyphen('-5-0,-')); console.log(replaceHyphen('--50,00')); console.log(replaceHyphen('50,--'));设置闹钟,如下所示?尝试一下。

PendingIntent.FLAG_UPDATE_CURRENT

希望这对你有用!!

答案 1 :(得分:0)

经过多次尝试,我决定不使用BroadcastReceiver而是使用IntentServices。 这是正确的代码和解决方案:

 @Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button:
            mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    mcurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
                    mcurrentTime.set(Calendar.MINUTE, selectedMinute);
                    setAlarm();

                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle(R.string.orario);
            mTimePicker.show();
            break;

private void setAlarm(){
    int id = (int) System.currentTimeMillis();
    Intent intent = new Intent(this, NotificationAlarm.class);
    intent.putExtra("Farmaco",editText.getText().toString());
    PendingIntent pendingIntent = PendingIntent.getService(this,id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mcurrentTime.getTimeInMillis(),5*60*1000, pendingIntent);
    }
    Log.d("Time", String.valueOf(mcurrentTime.getTimeInMillis()));
}

这是通知类:

public class NotificationAlarm extends IntentService {
String s;
int mNotificationId;
Random r = new Random();
public NotificationAlarm(){
    super("HelloNotificationService");

}

@Override
protected void onHandleIntent(Intent intent) {

    Notification.Builder mBuilder =
            new Notification.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.pill)
                    .setContentTitle(getApplicationContext().getString(R.string.titolo_notifica))
                    .setContentText(getApplicationContext().getString(R.string.descr_notifica)+" "+s)
                    // .setContent(remoteViews)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setVisibility(1);//1 è uguale a VISIBILITY_PUBLIC
    // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.html#VISIBILITY_PUBLIC

    mNotificationId = r.nextInt(10000); //assegno un id casuale ad ogni notifica affinchè non siano sovrascritte
    Intent notificationIntent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),(int)System.currentTimeMillis(),notificationIntent,PendingIntent.FLAG_ONE_SHOT);
    mBuilder.setContentIntent(pendingIntent);
    Log.d("IDNOT",Integer.toString(mNotificationId));

// Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr =
            (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);

// Builds the notification and issues it.
    mNotifyMgr.notify(mNotificationId, mBuilder.build());
    stopSelf();
}

public int onStartCommand(Intent intent, int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    s = intent.getStringExtra("Farmaco");
    return START_STICKY;
}
}
相关问题