Подтвердить что ты не робот

Уведомления Android с кнопками на нем

Я пытаюсь сделать уведомление с двумя кнопками на нем:

  • возвращает меня к активности
  • другой закрывает его

Кто-нибудь понял, как поймать событие нажатия кнопки (помните, что действие приостановлено)?

4b9b3361

Ответ 1

Я рад опубликовать его! После работы всю ночь я что-то нашел. Итак, мы идем!

1. Создайте файл макета xml для вашего уведомления.

2. Создайте уведомление с помощью Notification.Builder. После добавления всего, что вы хотите (значки, звуки и т.д.), Выполните следующее:

        //R.layout.notification_layout is from step 1

        RemoteViews contentView=new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);

        setListeners(contentView);//look at step 3

        notification.contentView = contentView;

3. Создайте метод setListeners. Внутри этого метода вы должны написать это:

    //HelperActivity will be shown at step 4

    Intent radio=new Intent(ctx, packagename.youractivity.class);  
    radio.putExtra("AN_ACTION", "do");//if necessary

    PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
    //R.id.radio is a button from the layout which is created at step 2  view.setOnClickPendingIntent(R.id.radio, pRadio); 

    //Follows exactly my code!
    Intent volume=new Intent(ctx, tsapalos11598712.bill3050.shortcuts.helper.HelperActivity.class);
    volume.putExtra("DO", "volume");</p>

    //HERE is the whole trick. Look at pVolume. I used 1 instead of 0.
    PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
    view.setOnClickPendingIntent(R.id.volume, pVolume);

4. Для моих требований я использовал HelperActivity, который отвечает на намерения. Но для вас я не думаю, что это необходимо.

Если вам нужен полный исходный код, вы можете просмотреть его или загрузить с моего репозитория git. Код предназначен для личного использования, поэтому не ожидайте, что прочитайте великолепный код с большим количеством комментариев. https://github.com/BILLyTheLiTTle/AndroidProject_Shortcuts

ВСЕ ВЫШЕ, ОТВЕТИТ ВОПРОС ОБ УБЫТКЕ СОБЫТИЙ ОТ РАЗНЫХ КНОПКОВ.

Об отмене уведомления я перенаправляю вас сюда

Как удалить уведомление в Android

Не забудьте использовать идентификатор, который вы проанализировали при методе уведомления, когда вы вызывали уведомление в первый раз

Ответ 2

Что касается ICS, вопрос просто ответить, потому что требуемое поведение отражает уведомление по умолчанию: вы можете закрыть уведомление, прокручивающее его вправо, и вы можете определить, какая деятельность, чтобы отправить пользователя, когда он нажимает его, просто используя PendingIntent:

// The PendingIntent to launch our activity if the user selects this
// notification.  Note the use of FLAG_CANCEL_CURRENT so that, if there
// is already an active matching pending intent, cancel it and replace
// it with the new array of Intents.
PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
        makeMessageIntentStack(this, from, message), PendingIntent.FLAG_CANCEL_CURRENT);

код, взятый из http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Ответ 3

Если вы хотите назначить определенное намерение кнопке:

views.setOnClickPendingIntent(R.id.your_button_id, pendingIntent);

Я предполагаю, что вам нужно только одно намерение отправляться при нажатии кнопки, поэтому вам нужно ИЗБЕЖАТЬ настройки основного уведомления

notification.contentIntent = yourPendingIntent;

В противном случае (если вы установите "notification.contentIntent = pendingIntent;", как обычно) будут вызваны оба намерения, которые могут быть не такими, которые вы хотите/ожидаете.

Если вы все еще хотите, чтобы другие части уведомления вызывали это общее намерение (или любое другое), вы можете использовать один и тот же метод назначения назначения за просмотр, как указано выше. Не забудьте установить

android:clickable="true"

для любого вида, на которое вы хотите отслеживать onClick() для.

Вы можете отслеживать эти намерения своими дополнениями в своей деятельности. Если, вы называете свою основную/запускающую деятельность, чем вы будете отслеживать их здесь (как это происходит из javadoc для этого метода):

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Bundle data = intent.getExtras();

    if (data != null && data.containsKey(YOUR_INTENT_KEY_SOURCE_CONSTANT)) {
       // process your notification intent
    }

    // go on with smth else
}

Ответ 4

Вы можете просто добавить кнопки действий в Notification, установив действие на Notification.Builder и определяя PendingIntent для каждого действия

ниже приведен пример кода:

    NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle("My notification")
                .setContentText("Hello World!")
       .addAction(R.drawable.action_posetive,"posetive",PendingIntent.getActivity(0,intent,0))
.addAction(R.drawable.action_clear,"clear",PendingIntent.getActivity(0,intent,0));
        NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());

Ответ 5

Здесь приведен полный пример.

    //Add this code to onCreate or some onclick Buttton
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
    long when = System.currentTimeMillis();
    builder.setSmallIcon(R.drawable.ic_notification);
    Intent notificationIntent = new Intent(getApplicationContext(), notificationActivity.class).putExtra("notification", "1");
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    Notification notification = builder.getNotification();
    notification.when = when;

    RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_view);
    remoteViews.setTextViewText(R.id.tvName, "New Name");
    listener(remoteViews,getApplicationContext());


    notification.contentView = remoteViews;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    manager.notify(1, notification);

а затем вы можете определить метод слушателя:

    public void listener(RemoteViews remoteViews, Context context) {
    // you have to make intetns for each action (your Buttons)
    Intent intent = new Intent("Accept");
    Intent intent2 = new Intent("Reject");

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1,intent,0);
    PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context,1,intent2,0);

    // add actions here !
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("Accept");
    intentFilter.addAction("Reject");


    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("Accept")){
                Toast.makeText(context, "Accepted !!", Toast.LENGTH_SHORT).show();
            } else if(intent.getAction().equals("Reject")) {
                Toast.makeText(context, "Rejected !!", Toast.LENGTH_SHORT).show();
            }
        }
    };

    context.registerReceiver(receiver,intentFilter);
    remoteViews.setOnClickPendingIntent(R.id.ivRequest,pendingIntent);
    remoteViews.setOnClickPendingIntent(R.id.ivReject,pendingIntent2);

}

и вот макет notification_view, чтобы окупить ваше уведомление.

    <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="Request from "
    />

<TextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginStart="15dp"
    android:layout_toRightOf="@id/textView"
    android:text="Amin"
    />

<ImageView
    android:id="@+id/ivRequest"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:src="@drawable/notification"
    />

<ImageView
    android:id="@+id/ivReject"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginEnd="10dp"
    android:layout_toLeftOf="@id/ivRequest"
    android:layout_centerVertical="true"
    android:src="@drawable/trash"
    />

  </RelativeLayout>