Search code examples
androidandroid-intentandroid-mediaplayerandroid-notificationsandroid-4.2-jelly-bean

Android Call Method from Notification bar Intent


I have the following (simplified) code in my android MainActivity.java class

case R.id.menu_stop:
    stopPlaying();
  return true;

How can I call the stopPlaying(), using an intent when an action button is pressed in a Jelly Bean notification? The notification is built in my StreamingService.java class. I can get action buttons working that fire off email, phone and SMS intents, I just don't know how to call methods in my code.

My code in the stopPlaying() method is as follows

private void stopPlaying() {
    Intent intent = new Intent(this, StreamingService.class);
    stopService(intent);
}

Solution

  • You will want to use the Broadcast/Receiver design pattern.

    Here's a good tutorial to get you started: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html

    Basically, you will want to write a receiver and register it in your service. Then, when the button in your notification is pressed, you want to fire off the broadcast (which takes an intent) while your service's receiver is waiting. When it receives the broadcast (basically instantaneously), it can then call your stopPlaying() method.