Как закрыть уведомление после нажатия кнопки действие



начиная с уровня API 16 (Jelly Bean), есть возможность добавлять действия в уведомление с помощью



builder.addAction(iconId, title, intent);


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



notification.flags = Notification.FLAG_AUTO_CANCEL;


или



builder.setAutoCancel(true);


но очевидно, что это не имеет ничего общего с действиями, связанными с уведомлением.



какие-то намеки? Или это еще не часть API? Я ничего не нашел.

744   6  

6 ответов:

когда вы вызывали notify в диспетчере уведомлений, вы дали ему идентификатор-это уникальный идентификатор, который вы можете использовать для доступа к нему позже (это из диспетчера уведомлений:

notify(int id, Notification notification)

чтобы отменить, вы бы позвонили:

cancel(int id)

С тем же идентификатором. Итак, в основном, вам нужно отслеживать идентификатор или, возможно, поместить идентификатор в пакет, который вы добавляете к намерению внутри PendingIntent?

обнаружил, что это проблема при использовании уведомления дисплея Lollipop'S Heads Up. Смотрите руководство по проектированию. Вот полный (ish) код для реализации.

до сих пор наличие кнопки "уволить" было менее важным, но теперь это больше в вашем лице.

heads up notification

создание уведомления

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

NotificationActivity

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (атрибуты, необходимые для предотвращения SystemUI от фокусировки на задний стек)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>

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

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

кроме того, если вы запускаете широковещательный приемник с кнопки, ящик уведомлений не закрывается.

Я в конечном итоге создавая новую NotificationActivity в решать эти вопросы. Это промежуточное действие без какого-либо пользовательского интерфейса отменяет уведомление, а затем запускает действие, которое я действительно хотел начать с уведомления.

Я опубликовал пример кода в должности щелчок Android Notification Actions не закрывает ящик уведомлений.

вы всегда можете cancel() the Notification из того, что вызывается действием (например, в onCreate() из деятельности, привязанной к PendingIntent вы addAction()).

В моем opninion с помощью BroadcastReceiver это более чистый способ отменить уведомление:

В AndroidManifest.XML-код:

<receiver 
    android:name=.NotificationCancelReceiver" >
    <intent-filter android:priority="999" >
         <action android:name="com.example.cancel" />
    </intent-filter>
</receiver>

в файле java:

Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Action actions[] = new NotificationCompat.Action[1];


NotificationCancelReceiver

public class NotificationCancelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Cancel your ongoing Notification
    };
}

просто вставляем эту строку :

 builder.setAutoCancel(true);

и полный код :

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
    builder.setContentTitle("Notifications Title");
    builder.setContentText("Your notification content here.");
    builder.setSubText("Tap to view the website.");
    Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder.setAutoCancel(true);
    // Will display the notification in the notification bar
    notificationManager.notify(1, builder.build());

Comments

    Ничего не найдено.