2013-09-30 5 views
4

Я пытаюсь выполнить какое-то действие, например, приостановить музыку, воспроизвести музыку при нажатии кнопки пользовательского уведомления в android. В настоящее время я делаю это таким образом,Выполнение действия на кнопке Нажмите в пользовательском уведомлении: Android

int icon = R.drawable.ic_launcher; 
    long when = System.currentTimeMillis(); 
    Notification notification = new Notification(icon, "Custom Notification", when); 

    NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 

    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.layout); 
    contentView.setTextViewText(R.id.textView1, "Custom notification"); 
    contentView.setOnClickPendingIntent(R.id.button1, pIntent); 
    notification.contentView = contentView; 

    Intent notificationIntent = new Intent(this, MainActivity.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
    notification.contentIntent = contentIntent; 

    notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification 
    notification.defaults |= Notification.DEFAULT_LIGHTS; // LED 
    notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration 
    notification.defaults |= Notification.DEFAULT_SOUND; // Sound 

    mNotificationManager.notify(1, notification); 

Но это один берет меня на другой вид деятельности. Есть ли способ реализовать действие уведомления для одного и того же действия.

, например .. скажем я поднять notifcation, и когда пользователь нажимает на нее, то вместо того, чтобы взять меня к какой-либо деятельности, то ссылаться на какой-то регулярный метод в моей текущей деятельности/услуг

+0

Я дал ответ за то же самое по данной ссылке http://stackoverflow.com/questions/11270898/how-to-execute-a-method-by-clicking-a-notification/11271367#11271367 –

ответ

10

Прежде всего назначить намерение кнопок:

RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.player_notify_layout); 
    Intent buttonsIntent = new Intent(context, NotifyActivityHandler.class); 
    buttonsIntent.putExtra("do_action", "play"); 
    contentView.setOnClickPendingIntent(R.id.imgPlayPause, PendingIntent.getActivity(context, 0, buttonsIntent, 0)); 

Затем создать действие для обработки каждого действия, которое произошло путем уведомления:

public class NotifyActivityHandler extends Activity { 
      public static final String PERFORM_NOTIFICATION_BUTTON = "perform_notification_button"; 

      @Override 
      protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 

       String action = (String) getIntent().getExtras().get("do_action"); 
       if (action != null) { 
        if (action.equals("play")) { 
         // for example play a music 
        } else if (action.equals("close")) { 
         // close current notification 
        } 
       } 

       finish(); 
     } 
    } 

Наконец, следует отменить прекрасная деятельность в AndroidManifest.xml. Также вы можете проверить это link.

Надеюсь, это полезно для вас.

+0

Я реализовал это решение, но setOnClickPendingIntent не работает для меня, есть ли какое-либо решение для этого? – AndyN

Смежные вопросы