如何设置点击监听器以进行通知?

时间:2011-08-25 03:58:05

标签: android notificationmanager

我正在使用以下代码通过AlarmManager启动服务时启动通知:

nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "App";
CharSequence message = "Getting Latest Info...";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
    "Getting Latest Info...", System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
nm.notify(1, notif);

如何设置此项目的意图,以便当用户点击它时,它会启动某项活动?

3 个答案:

答案 0 :(得分:27)

至于yoshi24的评论,你可以设置这样的额外内容。

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

在进行待定意图

之前,您还需要注意这一点

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

<强>更新 这样的事情会对你有用

你的主要节目

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

在您的活动中

@Override
protected void onCreate(Bundle savedInstanceState) {
    processIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {     
    processIntent(intent);
};

private void processIntent(Intent intent){
    //get your extras
}

答案 1 :(得分:17)

您基本上需要将Activity类作为意图的一部分放入PendingIntent中。目前你的Intent是空的。要重定向到新活动,它应该是:

// 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);

答案 2 :(得分:9)

我做到了,

  • 我将Intent.FLAG_ACTIVITY_CLEAR_TOP添加到新意图

    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我这样做:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    if(getIntent().getExtras()!=null){
        Toast.makeText(this, "Click", Toast.LENGTH_SHORT).show();
    }
    
相关问题