未显示活动的通知点击事件?

时间:2013-01-19 16:35:28

标签: java android android-notifications

我想分配一个事件,该事件会在点击通知时触发,而不显示活动(如解释here)。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以通过注册广播接收器来完成此操作。这样,您可以在单击通知时在接收器中运行代码,而不显示任何UI(如果需要)。

基本接收者代码:

public class Provider extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        //Your code here

    }
}

在清单中:

<receiver android:name="Provider" />

通知的示例代码:

public static void showNotification(Context context) {
    CharSequence title = "title";
    CharSequence message = "text";

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(<image>, title, System.currentTimeMillis());
    notification.flags = Notification.FLAG_ONGOING_EVENT;

    Intent notificationIntent = new Intent(context, Provider.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, pendingIntent);
    notificationManager.notify(<notification id>, notification);
}