поймать удар, чтобы отклонить событие
37661 просмотра
3 ответа
Я использую уведомление Android, чтобы предупредить пользователя, когда служба завершена (успех или сбой), и я хочу удалить локальные файлы, когда процесс будет завершен.
Моя проблема в том, что в случае сбоя - я хочу дать пользователю возможность «повторить попытку». и если он решит не повторять и отклонить уведомление, я хочу удалить локальные файлы, сохраненные для целей процесса (изображения ...).
Есть ли способ отловить событие, касающееся отклонения уведомления?
Автор: Dror Fichman Источник Размещён: 12.11.2019 09:55Ответы (3)
138 плюса
DeleteIntent : DeleteIntent - это объект PendingIntent, который может быть связан с уведомлением и запускается при удалении уведомления, например:
- Пользовательское действие
- Пользователь Удалить все уведомления.
Вы можете установить Pending Intent для широковещательного приемника, а затем выполнить любое действие, которое вы хотите.
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
Размещён: 03.02.2013 10:39
80 плюса
Полностью смутый ответ (с благодарностью г-ну Ме за ответ):
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) Создайте ожидающее намерение, используя уникальный идентификатор для ожидающего намерения (здесь используется идентификатор уведомления), поскольку без этого те же дополнительные функции будут повторно использоваться для каждого события увольнения:
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);
Автор: Chris Knight
Размещён: 18.12.2013 11:55
0 плюса
Другая идея:
если вы обычно создаете уведомление, вам также нужны действия один, два или три из них. Я создал «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;
}
и, наконец, в том же NotificationManager есть функция выполнения:
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
}
Автор: HowardS
Размещён: 02.11.2017 12:51
Вопросы из категории :
- android Насколько хорошо отражает эмулятор Android Phone?
- android Как сохранить состояние активности Android с помощью сохранения состояния экземпляра?
- android Android: доступ к дочерним представлениям из ListView
- android Как вызвать SOAP веб-сервис на Android
- service Службы синхронизации Ado.net SyncSchema
- service Хранение паролей для внешних API - лучшая практика
- service Почему System.Threading.Timer останавливается сам по себе?
- service Веб-служба или служба Windows или интеграция SQL CLR?
- notifications WPF / WCF Push-уведомление
- notifications Есть ли способ уведомить IE об изменениях, внесенных в реестр через код?
- notifications Как получить уведомления о статусе сборки TFS?
- notifications Лучший способ сериализации NSData в шестнадцатеричную строку
- swipe Обнаружение касания пальцем по JavaScript на iPhone и Android
- swipe Превратите комикс в веб-приложение для iphone
- swipe Android: как обрабатывать жесты справа налево
- swipe Существующая библиотека для разбора информации о лицензиях водителей?
- temporary-files Как я могу создать временный файл с определенным расширением .NET?
- temporary-files Удаление созданных временных файлов при неожиданном выходе из bash
- temporary-files Как запретить vim создавать (и оставлять) временные файлы?
- temporary-files Как создать именованный временный файл в Windows на Python?