2015-03-08 2 views
0

У меня есть действие, которое вызывает помощника, где я создаю уведомление, которое будет всплывать в выбранное время. Он отлично работает.Удалить ожидающий сигнал тревоги/уведомление из службы

Я хочу создать другую функцию в другой деятельности, которая может удалить ожидающий сигнал перед появлением уведомления. Я пробовал много способов найти в Интернете, но ничего не получилось. Что я делаю не так?

// Add Alarm 
public class Helper { 
    public void SetAlarm(Activity activity, int requestCode, Calendar calendar, String title, ArrayList<PendingIntent> intentArray) { 
     AlarmManager alarmManager = (AlarmManager)activity.getSystemintent(Context.ALARM_intent); 

     Intent intent = new Intent(activity.getBaseContext(), MyReceiver.class); 
     intent.putExtra("title",title); 

     PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, requestCode, intent, 0); 
     alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
     intentArray.add(pendingIntent); 
    } 
} 


// Delete Alarm 
public class MyActivity extends Activity { 
    ProgressDialog progress; 
    // ... 
    public void Delete(int requestCode , String title) { 
     progress = ProgressDialog.show(this, getString(R.string.title), getString(R.string.text), true); 
     new Thread(new Runnable() { 
       @Override 
       public void run() 
       { 
       // .... 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() 
        { 
         try { 
          Intent intent = new Intent(getBaseContext(), MyReceiver.class); 
          intent.putExtra("title",title); // don't know if really needed 
          AlarmManager alarmManager = (AlarmManager)getSystemintent(Context.ALARM_intent); 
          PendingIntent pi = PendingIntent.getBroadcast(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
          alarmManager.cancel(pi); 
          // Tried that also - didn't work: 
          // PendingIntent.getBroadcast(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel(); 
          // pi.cancel(); 
         } 
         catch(Exception e) { 
          // ... 
         } 
         progress.dismiss(); 
        } 
       }); 
       } 
     }).start(); 
    } 
} 





// BroadcastReceiver 
public class MyReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     Intent newIntent = new Intent(context, MyAlarmService.class); 
     newIntent.putExtra("title", intent.getExtras().getString("title")); 
     context.startService(newIntent); 
    } 
} 

public class MyAlarmService extends Service 
{ 
    // ... 

    @SuppressWarnings("static-access") 
    @Override 
    public int onStartCommand(Intent intent, int flag, int startId) 
    { 
     super.onStartCommand(intent, START_STICKY, startId); 

     mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE); 
     Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class); 
     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 notification = new Notification.Builder(this.getApplicationContext()) 
      .setContentTitle(getString(R.string.app_name)) 
      .setContentText(getString(R.string.conText)) 
      .setWhen(System.currentTimeMillis()) 
      .setContentIntent(pendingNotificationIntent) 
      .build(); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

     mManager.notify(0, notification); 
     return START_STICKY; 
    } 
} 
+0

Вам необходимо предоставить тот же «Intent», когда вы отмените свой «PendingIntent». – Machado

+0

Это общая деятельность. Как я могу использовать одно и то же намерение? не могу ли я просто воссоздать его? – TamarG

+0

http://stackoverflow.com/questions/19593442/android-get-same-intent-from-different-activities – Machado

ответ

1

отмена намерение должно соответствовать первоначальному (действие, данные, тип, класс и категории одинаковы). Вы пытались вызвать PendingIntent.getBroadcast() без флагов? (0 вместо PendingIntent.FLAG_UPDATE_CURRENT). И убедитесь, что вы используете один и тот же код запроса.

+0

Действительно - я ошибочно использовал неправильный код запроса, и я не заметил! – TamarG

0

Создать свой сигнал тревоги, как это:

public static void createAlarm(Context context, Calendar calAlarm, String ALARM_ACTION_NAME) 
{ 
    try 
    { 
     AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 

     // Create an alarm intent 
     Intent alarmIntent = new Intent(ALARM_ACTION_NAME); 

     // Create the corresponding PendingIntent object 
     PendingIntent alarmPI = PendingIntent.getBroadcast(context, 0, alarmIntent, 0); 

     // cancel any alarms previously set 
     alarmMgr.cancel(alarmPI); 

     // Register the alarm with the alarm manager 
     alarmMgr.set(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), alarmPI); 

    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

И вы можете отменить это так:

public static void cancelAlarm(Context context, String ALARM_ACTION_NAME) 
{ 
    try 
    { 
     AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 

     // Create an alarm intent 
     Intent alarmIntent = new Intent(ALARM_ACTION_NAME); 

     // Create the corresponding PendingIntent object 
     PendingIntent alarmPI = PendingIntent.getBroadcast(context, 0, alarmIntent, 0); 

     // cancel any alarms previously set 
     alarmMgr.cancel(alarmPI); 

    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 
+0

Что такое ALARM_ACTION_NAME? – TamarG

+0

Строка, которую вы использовали для создания вашей тревоги ... – Christian

+0

Где вы используете MyReciever? Где вы создаете уведомление? – TamarG

Смежные вопросы