簡體   English   中英

如何在通知中添加點擊動作?

[英]How to add tap action on notification?

我想在通知中添加點擊動作(退出(完成))。 我正在制作一個包含幾個類的簡單應用,當我點擊通知時,我希望它們全部完成。 這是我的通知代碼:

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 class (這是我的停止服務代碼),但是我不確定這是否是正確的引用。

希望我的問題清楚。

您應該使用通知生成器:

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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM