Programing

스 와이프하여 이벤트 닫기

lottogame 2020. 10. 9. 08:44
반응형

스 와이프하여 이벤트 닫기


서비스가 완료되면 (성공 또는 실패) 사용자에게 알리기 위해 Android 알림을 사용하고 있으며 프로세스가 완료되면 로컬 파일을 삭제하고 싶습니다.

내 문제는 실패시 사용자에게 "재시도"옵션을 제공하고 싶다는 것입니다. 그리고 그가 재 시도하지 않고 알림을 취소하기로 선택하면 프로세스 목적으로 저장된 로컬 파일 (이미지 ...)을 삭제하고 싶습니다.

알림의 스 와이프하여 닫기 이벤트를 포착하는 방법이 있습니까?


DeleteIntent : DeleteIntent는 알림과 연결될 수있는 PendingIntent 개체이며 알림이 삭제되면 실행됩니다.

  • 사용자 별 작업
  • 사용자 모든 알림을 삭제합니다.

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

  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
         }

  }

완전히 플러시 된 답변 (답변에 대해 Mr. Me에게 감사) :

1) 스 와이프하여 닫기 이벤트를 처리 할 수신기를 만듭니다.

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) 매니페스트에 항목을 추가합니다.

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

3) 보류중인 인 텐트에 대한 고유 ID를 사용하여 보류중인 인 텐트를 생성합니다 (여기에서 알림 ID가 사용됨). 이렇게하지 않으면 각 해제 이벤트에 대해 동일한 추가 항목이 재사용됩니다.

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;
}

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);

또 다른 아이디어 :

일반적으로 알림을 생성하는 경우 하나, 둘 또는 세 가지 작업도 필요합니다. "NotifyManager"를 만들었습니다. 필요한 모든 알림을 만들고 모든 Intent 호출도받습니다. 따라서 모든 작업을 관리하고 한 곳에서 해제 이벤트를 잡을 수 있습니다.

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를 만들려면 다음을 사용하십시오 (NotificationManager에서).

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;
}

그리고 (NotificationManager에서) 다음과 같이 삭제 의도를 설정하는 데 사용합니다.

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;
}

and finally in the same NotificationManager is the perform function:

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
}

참고URL : https://stackoverflow.com/questions/14671453/catch-on-swipe-to-dismiss-event

반응형