1

Я создал уведомление, которое отображается в определенное время, но проблема в том, что каждый раз, когда я закрываю приложение (после префикса времени), отображается уведомление. Как я могу исправить эту проблему?Уведомление отображается каждый раз, когда я закрываю приложение

Это мой код: Home.class (фрагмент)

Calendar calend = Calendar.getInstance(); 
     calend.setTimeInMillis(System.currentTimeMillis()); 
     calend.set(Calendar.HOUR_OF_DAY, 9); 
     calend.set(Calendar.MINUTE, 27); 
     calend.set(Calendar.SECOND, 0); 
     Intent myIntent = new Intent(getActivity(), MyReceiver.class); 
     pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0); 
     AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); 

MyReceiver.class

public class MyReceiver extends BroadcastReceiver 
{ 

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


     Intent service1 = new Intent(context, MyAlarmService.class); 
     context.startService(service1); 

    } 
} 

MyAlarmService.class

public class MyAlarmService extends Service 
{ 

    private NotificationManager mManager; 

    @Override 
    public IBinder onBind(Intent arg0) 
    { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() 
    { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
    } 

    @SuppressWarnings({ "static-access", "deprecation" }) 
    @Override 
    public void onStart(Intent intent, int startId) 
    { 
     super.onStart(intent, startId); 

     mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE); 
     Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class); 

     Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis()); 
     intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent); 

     mManager.notify(0, notification); 
    } 

    @Override 
    public void onDestroy() 
    { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
    } 

} 
+0

Просьба указать, где вы разместили вышеуказанный код. –

+0

На самом деле вы создали 'Alarm' на' alarmManager.setRepeating', который повторит его. Отмените его, когда вы закроете приложение, когда Тревога запускается в 'Сервис' – hrskrs

+0

**« Как я могу исправить эту проблему? »**: Отменить будильник, когда вы покидаете приложение. – Squonk

ответ

0

Вы можете прочесть в этом сообщении: Will AlarmManager work if my application is not running? AlarmManager предупреждает вас, пока устройство не перезагрузится, или если вы убили приложение. Удалить его из последнего списка убьет приложение.

Это не объясняет, почему отображается уведомление, но я предполагаю, что система выполнит ваш запрос во время убийства. Он должен просто удалить его, но, возможно, (нет доказательств здесь), он предпочитает посылать вещание insteed

+0

, но я пытаюсь убить приложение за минуту до установленного времени уведомление и когда это было подходящее время, когда было показано уведомление, даже если я убью приложение. И я вижу, что уведомление отображается также после того, как я убью приложение как в тот момент, когда я закрываю приложение, и некоторое время спустя. – Slaiv206

+0

Можете ли вы отредактировать свой вопрос со всем тестом, который вы сделали. Потому что это не ясно сейчас. – AxelH

2

У меня есть ответ на этот вопрос.

Не используйте сервис для этого. вам просто нужно написать приведенный ниже код в классе MyReceiver, и он не даст вам уведомления, когда вы убьете приложение из диспетчера задач.

public class AlarmReceiver extends BroadcastReceiver { 
     private NotificationManager mManager; 

     private static final int MY_NOTIFICATION_ID = 1; 
     private static final String TAG = "AlarmNotificationReceiver"; 

     // Notification Text Elements 
     private final CharSequence tickerText = "its ok?"; 
     private final CharSequence contentTitle = " Reminder1"; 
     private final CharSequence contentText = "reminder content"; 

     // Notification Action Elements 
     private Intent mNotificationIntent; 
     private PendingIntent mContentIntent; 

     @Override 
     public void onReceive(Context context, Intent intent) { 
     // When our Alaram time is triggered , this method will be excuted (onReceive) 



      mNotificationIntent = new Intent(context, MyView.class); 

      // The PendingIntent that wraps the underlying Intent 
      mContentIntent = PendingIntent.getActivity(context, 0,mNotificationIntent,PendingIntent.FLAG_UPDATE_CURRENT); 

      // Build the Notification 
      Notification.Builder notificationBuilder = new Notification.Builder(
        context).setTicker(tickerText) 
        .setSmallIcon(android.R.drawable.stat_sys_warning) 
        .setAutoCancel(true).setContentTitle(contentTitle) 
        .setContentText(contentText).setContentIntent(mContentIntent); 

      // Get the NotificationManager 
      NotificationManager mNotificationManager = (NotificationManager)context 
        .getSystemService(Context.NOTIFICATION_SERVICE); 

      // Pass the Notification to the NotificationManager: 
      mNotificationManager.notify(MY_NOTIFICATION_ID, 
        notificationBuilder.build()); 

     } 

    } 
+0

На самом деле это работает для меня. Но может ли кто-нибудь дать объяснение тому же? – Swapnil