Android: Click event for Status bar notification

前端 未结 2 1115
春和景丽
春和景丽 2021-02-07 17:38

I\'ve got the following code to create a status bar notification:

public void txtNotification(int id, String msg){
    NotificationManager manager = (Notificatio         


        
相关标签:
2条回答
  • 2021-02-07 18:20

    I think the best way for you to handle a click on the notification (maybe the only way?) is to define a method within the class your PendingIntent calls (MainActivity in this case). You can modify your intent before passing it into getActivity() to include the id of the notification:

    // The PendingIntent will launch activity if the user selects this notification
    Intent intent = new Intent(this, MainActivity.class)
    intent.putExtra("yourpackage.notifyId", id);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);
    

    Then watch for this intent within MainActivity and call the method you defined within the class to handle the notification. You can extract the id from the incoming Intent.

    Update:

    In order for your Activity to handle the notification, you'll need to first define the Activity in your AndroidManifest.xml file, including any intent filters you need. Then in your Activity's onStart() you can extract the extras from the incoming intent, and act upon that data. This is a high level overview, so I suggest you read parts of the Dev Guide to familiarize yourself with the concepts. The following page is a good place to start:

    http://developer.android.com/guide/topics/fundamentals.html

    Also "yourpackage" should be replaced with the name of the package that includes your Class, such as "com.project.foo".

    0 讨论(0)
  • 2021-02-07 18:35

    For dummies like myself: Getting this yourpackage.notifyId at MainActivity:

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Bundle intent_extras = getIntent().getExtras();
            if (intent_extras != null && intent_extras.containsKey("yourpackage.notifyId"))
            {
              //Do the codes
            }
    
    }
    

    In my case - used it to determine who is opening my mainactivity, user or a call from notification, cteated by GcmIntentService... P.S. I've used names without "youpackage", works fine too.

    0 讨论(0)
提交回复
热议问题