2013-02-03 3 views
66

서비스가 완료되면 사용자에게 알리기 위해 Android 알림을 사용하고 프로세스가 완료되면 로컬 파일을 삭제하려고합니다.스 와이프를 catch하여 이벤트를 닫습니다.

내 문제는 실패 할 경우 사용자에게 "다시 시도"옵션을 허용하려는 것입니다. 재시도하지 않고 알림을 닫지 않으면 처리 목적으로 저장된 로컬 파일 (이미지 ...)을 삭제하려고합니다.

알림의 스 와이프 해지 이벤트를 잡는 방법이 있습니까?

답변

104

DeleteIntent : DeleteIntent 알림과 연관 될 수 있으며, 알림이 삭제됩니다 때 에테르에 의해 해고 가져옵니다 PendingIntent 객체입니다 :

  • 사용자 특정 작업
  • 사용자는 모든 알림을 삭제 .

브로드 캐스트 수신기에 보류 의도를 설정 한 다음 원하는 모든 작업을 수행 할 수 있습니다.

1) 슬쩍 간을 처리하기 위해 수신기를 만듭니다

Intent intent = new Intent(this, MyBroadcastReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0); 
    Builder builder = new Notification.Builder(this): 
..... code for your notification 
    builder.setDeleteIntent(pendingIntent); 

MyBroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      .... code to handle cancel 
     } 

    } 
+0

작품 :) 고마워요! –

+5

이것은 늦었습니다. 'builder.setAutoCancel (true);' 사용자가 알림을 클릭하고 취소 될 때 delete-Intent가 트리거되지 않기 때문에 비슷한 방법으로 알려주고 싶습니다. –

+1

@dev_android checkout http :// /developer.android.com/reference/android/app/Notification.Builder.html#setContentIntent (android.app.PendingIntent) –

66

A는 완전히 (대답 씨 나 덕분에) 대답을 플러시 이벤트 기각 :

public class NotificationDismissedReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     int notificationId = intent.getExtras().getInt("com.my.app.notificationId"); 
     /* Your code to handle the event here */ 
    } 
} 

2) 항목을 추가하십시오

private PendingIntent createOnDismissedIntent(Context context, int notificationId) { 
    Intent intent = new Intent(context, NotificationDismissedReceiver.class); 
    intent.putExtra("com.my.app.notificationId", notificationId); 

    PendingIntent pendingIntent = 
      PendingIntent.getBroadcast(context.getApplicationContext(), 
             notificationId, intent, 0); 
    return pendingIntent; 
} 
: R 매니페스트 : 같은 엑스트라 각 해고 이벤트를 다시 사용됩니다이없이 같은

<receiver 
    android:name="com.my.app.receiver.NotificationDismissedReceiver" 
    android:exported="false" > 
</receiver> 

3) (알림 ID가 여기에 사용되는) 보류중인 의도에 대한 고유 ID를 사용하여 보류중인 의도를 만들기

4) 알림을 구축 :

Notification notification = new NotificationCompat.Builder(context) 
       .setContentTitle("My App") 
       .setContentText("hello world") 
       .setWhen(notificationTime) 
       .setDeleteIntent(createOnDismissedIntent(context, notificationId)) 
       .build(); 

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
notificationManager.notify(notificationId, notification); 
+0

멋지게 끝난 젠체하는 사람! –

+0

나에게 도움이되지 않았는데, 항상 "수신자를 인스턴스화 할 수 없습니다 .... 인자가 없습니다."라는 오류가 발생했습니다. 내가하지만 방송 수신기의 등록과 다른 유사한 솔루션을 구현 한 후에 만 ​​해결 : http://stackoverflow.com/questions/13028122/how-to-use-delete-intent-to-perform-some-action-on -clear-notification –

+0

이것은 나를 위해 작동합니다. 그러나 알림을 클릭하면 이벤트를 호출 할 수 없습니다. 어떻게하면 클릭 이벤트를들을 수 있습니까? –

0

또 다른 아이디어 :

전 f 일반적으로 통지를 작성하는 경우, 하나, 둘 또는 세 개의 조치가 필요합니다. 필자가 필요한 모든 통지를 작성하고 모든 Intent 호출을 수신하는 "NotifyManager"를 작성했습니다. 그래서 나는 모든 행동을 관리 할 수 ​​있고 한 장소에서 이벤트를 포착 할 수 있습니다.

private PendingIntent createOnDismissedIntent(Context context) { 
    Intent   intent   = new Intent(context, NotifyPerformMailService.class).setAction("ACTION_NOTIFY_DELETED"); 
    PendingIntent pendingIntent = PendingIntent.getService(context, SOME_NOTIFY_DELETED_ID, intent, 0); 

    return pendingIntent; 
} 

을하고 난 (노 티피 케이션의)이 같은 삭제 의도 설정하는 데 사용하는 :

public class NotifyPerformService extends IntentService { 

@Inject NotificationManager notificationManager; 

public NotifyPerformService() { 
    super("NotifyService"); 
    ...//some Dagger stuff 
} 

@Override 
public void onHandleIntent(Intent intent) { 
    notificationManager.performNotifyCall(intent); 
} 

deleteIntent이 (노 티피 케이션에)이 사용 만들 수

private NotificationCompat.Builder setNotificationStandardValues(Context context, long when){ 
    String       subText = "some string"; 
    NotificationCompat.Builder  builder = new NotificationCompat.Builder(context.getApplicationContext()); 


    builder 
      .setLights(ContextUtils.getResourceColor(R.color.primary) , 1800, 3500) //Set the argb value that you would like the LED on the device to blink, as well as the rate 
      .setAutoCancel(true)             //Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. 
      .setWhen(when)               //Set the time that the event occurred. Notifications in the panel are sorted by this time. 
      .setVibrate(new long[]{1000, 1000})          //Set the vibration pattern to use. 

      .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) 
      .setSmallIcon(R.drawable.ic_white_24dp) 
      .setGroup(NOTIFY_GROUP) 
      .setContentInfo(subText) 
      .setDeleteIntent(createOnDismissedIntent(context)) 
    ; 

    return builder; 
} 

public void performNotifyCall(Intent intent) { 
    String action = intent.getAction(); 
    boolean success = false; 

    if(action.equals(ACTION_DELETE)) { 
     success = delete(...); 
    } 

    if(action.equals(ACTION_SHOW)) { 
     success = showDetails(...); 
    } 

    if(action.equals("ACTION_NOTIFY_DELETED")) { 
     success = true; 
    } 


    if(success == false){ 
     return; 
    } 

    //some cleaning stuff 
} 
01 : 최종적으로 동일한 티피에서 수행 함수
관련 문제