简体   繁体   English

如何在通知中添加点击动作?

[英]How to add tap action on notification?

I want to add a tap action (exit (finish)) to a notification. 我想在通知中添加点击动作(退出(完成))。 I'm making a simple app with several classes, and I want them all finished when I tap the notification. 我正在制作一个包含几个类的简单应用,当我点击通知时,我希望它们全部完成。 Here is my notification code: 这是我的通知代码:

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

I'm making a reference to stopservice class (where it is my stop service code) on Intent nid , but I'm not quite sure if it's a correct reference. 我在Intent nid上引用了stopservice class (这是我的停止服务代码),但是我不确定这是否是正确的引用。

hope that my question is clear. 希望我的问题清楚。

You should be using a notification builder: 您应该使用通知生成器:

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

Your code is set to launch the Activity "stopservice" (which technically should be "StopService" with naming conventions), are you sure that class is an Activity? 您的代码设置为启动活动“ stopservice”(从技术上来说,它应为“ StopService”,具有命名约定),您确定该类是活动吗?

Also, make sure your Activity is registered in your app's manifest: 另外,请确保您的活动已在您的应用清单中注册:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM