2016-03-17 2 views
1

Я разрабатываю приложение для планирования событий, и сейчас я работаю над функцией назначения объекта гостю. Когда объект назначен, уведомление направляется гостю, спрашивая его, может ли он взять требуемый предмет. В зависимости от ввода пользователя HTTP-запрос отправляется обратно на сервер, обновляя статус элемента (принося/не принося).Android Notification Action Button Click Listener

Я как бы застрял в ответ на щелчок на кнопках действия уведомления, так как я не совсем понял, как это работает. Мне удалось показать кнопки действий, но не смог понять, как реагировать на нажатие на них. Поскольку я видел онлайн, ответ на кнопки действия уведомления управляется PendingIntent, который я не мог понять, как он работает, и как я могу использовать его для отправки HTTP-запросов в соответствии с нажатой кнопкой.

Я был бы рад за помощь и совет.

[Это пример уведомления отправляется пользователю.] [

Это метод, который уведомляет пользователя:

private void notifyUser(Bundle data) { 
    ... 
    //Notification configuration. 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setSmallIcon(...) 
      .setLargeIcon(...) 
      .setContentTitle(...) 
      .setContentText(...) 
      .setAutoCancel(...) 
      .setSound(...); 

     //Get the item data from the request sent to the GCM server. 
     Item item = GsonFactory.getGson() 
       .fromJson(data.getString("data"), Item.class); 

     //This is the part that I do not understand... 
     notificationBuilder 
       .addAction(R.drawable.ic_close_black, "No", null) 
       .addAction(R.drawable.ic_done_black, "Yes", null); 

    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.notify(0, notificationBuilder.build()); 
} 

Спасибо в передовых!

ответ

0

Вы должны установить объект PendingIntent для своих действий, чтобы пользователь выполнял какие-либо действия на кнопках уведомлений, которые устраивают конкретные намерения. Ожидается, что PendingIntent может быть установлен для Activity, Broadcast Receiver or Service. Если вы хотите, чтобы показать активность, когда пользователь нажимает на кнопку уведомления, то вы можете использовать -

Intent intent = new Intent(this, NotificationReceiverActivity.class); 
    intent.putExtra(<key>, item); //If you wan to send data also 
    PendingIntent pIntent = PendingIntent.getActivity(this, <notification_id>, intent, 0); //<notification_id> may be any number 

И установить это намерение на ваши действия уведомления -

notificationBuilder 
       .addAction(R.drawable.ic_close_black, "No", pIntent) 
       .addAction(R.drawable.ic_done_black, "Yes", pIntent); 
0

Я hoope это может помочь вам

// Exemple уведомления с помощью кнопки частного статического ничтожной scheduleNotificationWithButton (контекст Context, строка сообщения) {

int notifReCode = 1; 

//What happen when you will click on button 
Intent intent = new Intent(context, MainActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_ONE_SHOT); 

//Button 
NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Go", pendingIntent).build(); 

//Notification 
Notification notification = new NotificationCompat.Builder(context) 
     .setSmallIcon(R.mipmap.ic_launcher) 
     .setContentText("Back to Application ?") 
     .setContentTitle("Amazing news") 
     .addAction(action) //add buton 
     .build(); 

//Send notification 
NotificationManager notificationManager = (NotificationManager) 
     context.getSystemService(Context.NOTIFICATION_SERVICE); 
notificationManager.notify(1, notification);