Android服务通知onclick

时间:2015-03-08 10:36:50

标签: java android android-activity android-service

我有一个前台服务,并且当用户点击通知时,我想让通知打开MainActivity。

在自定义Service类中创建通知的方法是:

public void setForeground(final int notificationID, final int notificationIconID,
        final String notificationTickerText,
        final String notificationTitle, final String notificationText){
    Notification notification = new Notification(notificationIconID, notificationTickerText,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, notificationTitle,
            notificationText, PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()), 0));
    startForeground(notificationID, notification);
}

如何修改它以包含打开(如果MainActivity当前处于打开状态)或在Notification点击功能上启动MainActivity?

1 个答案:

答案 0 :(得分:1)

如果您想点击Activity打开任何notification,那么您需要实施 TaskStackBuilder

Intent resultIntent = new Intent(this, ResultActivity.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0,
                                    PendingIntent.FLAG_UPDATE_CURRENT);

mBuilder.setContentIntent(resultPendingIntent);