How to set click listener for notification?

后端 未结 3 1044
别那么骄傲
别那么骄傲 2020-12-01 09:06

I am using the following code to launch a notification when a Service is started Via AlarmManager:

nm = (NotificationManager) this.getSystemService(Context.N         


        
相关标签:
3条回答
  • 2020-12-01 09:58

    I did it,

    • I add Intent.FLAG_ACTIVITY_CLEAR_TOP to new intent

      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      Notification notification = new Notification(R.drawable.ic_launcher,
              "A new notification", System.currentTimeMillis());
      // Hide the notification after its selected
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      
      Intent intent = new Intent(this, NoficationDemoActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      Bundle bundle = new Bundle();
      bundle.putString("buzz", "buzz");
      intent.putExtras(bundle);
      PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
      notification.setLatestEventInfo(this, "This is the title",
              "This is the text", activity);
      notification.number += 1;
      notificationManager.notify(0, notification);
      
    • Oncreate i do as follow:

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      if(getIntent().getExtras()!=null){
          Toast.makeText(this, "Click", Toast.LENGTH_SHORT).show();
      }
      
    0 讨论(0)
  • 2020-12-01 10:02

    As for yoshi24's comment, you may be able to set extras like this.

    final Intent intent = new Intent(this, MyActivity.class);
    intent.setData(data);
    intent.putExtra("key", "value");
    final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
    

    You need to be aware of this as well before going for pending intents

    https://stackoverflow.com/questions/1198558/how-to-send-parameters-from-a-notification-click-to-an-activity

    UPDATE some thing like this will work for you

    int your mainfest

    <activity android:name=".MyActivity" android:launchMode="singleTop" ... />
    

    in your activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        processIntent(getIntent());
    }
    
    @Override
    protected void onNewIntent(Intent intent) {     
        processIntent(intent);
    };
    
    private void processIntent(Intent intent){
        //get your extras
    }
    
    0 讨论(0)
  • 2020-12-01 10:03

    You basically need to put the Activity class as part of your intent into your PendingIntent. Currently your Intent is empty. To redirect to new activity, it should be:

    // This line of yours should contain the activity that you want to launch. 
    // You are currently just passing empty new Intent()
    PendingIntent contentIntent = 
        PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
    

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