Android 如何在通知时添加点击操作?

Android 如何在通知时添加点击操作?,android,android-notifications,Android,Android Notifications,我想在通知中添加点击操作(退出(完成))。 我正在制作一个包含几个类的简单应用程序,我希望在点击通知时将它们全部完成。 这是我的通知代码: mMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification n = new Notification(); n.icon = R.drawable.ic_launcher; n.tickerText = "Ta

我想在通知中添加点击操作(退出(完成))。 我正在制作一个包含几个类的简单应用程序,我希望在点击通知时将它们全部完成。 这是我的通知代码:

mMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification n = new Notification();
        n.icon = R.drawable.ic_launcher;
        n.tickerText = "Tap this notification to exit";
        n.when = System.currentTimeMillis();
        Intent nid = new Intent(MainActivity.this, stopservice.class);
        PendingIntent ci = PendingIntent.getActivity(this, 0, nid,PendingIntent.FLAG_UPDATE_CURRENT);
        CharSequence ct = "TAP";
        CharSequence tt = "Tap here to exit";
        n.setLatestEventInfo(this,ct,tt,ci);
        mMN.notify(NOTIFICATION_ID, n);
我在
Intent-nid
上引用了
stopservice类
(这里是我的stopservice代码),但我不确定这是否是正确的引用


希望我的问题很清楚。

您应该使用通知生成器:

mMN = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        

Intent nid = new Intent(MainActivity.this, stopservice.class);
// If you were starting a service, you wouldn't using getActivity() here
PendingIntent ci = PendingIntent.getActivity(MainActivity.this, NOTIFICATION_ID, nid, PendingIntent.FLAG_UPDATE_CURRENT);

Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setContentTitle("TAP")
        .setContentText("Tap here to exit")
        .setTicker("Tap this notification to exit")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(ci)
        .setAutoCancel(true); // auto cancel means the notification will remove itself when pressed

mMN.notify(NOTIFICATION_ID, builder.getNotification());
您的代码设置为启动活动“stopservice”(从技术上讲,它应该是具有命名约定的“stopservice”),您确定该类是活动吗

另外,确保在应用程序清单中注册了您的活动:

<activity android:name="[package-name].stopservice" android:label="@string/app_name"/>

您能否进一步澄清一下您的目标?您是否试图在通知上实现类似于
onClickListener
的功能?如果是这样,就不一定有直接的方法。您需要创建一个
意图
,以完成您的操作。