gpt4 book ai didi

android - 在不打开应用程序的情况下通过操作按钮关闭正在进行的 Android 通知

转载 作者:IT老高 更新时间:2023-10-28 23:16:50 30 4
gpt4 key购买 nike

我有一个应用程序,它有一个持续的通知来帮助内存。我希望能够使用其中一个操作按钮关闭此通知,但我不想在按下按钮时打开应用程序。我更喜欢使用内置的通知操作按钮,而不是创建 RemoteViews 对象来填充通知。我看到一篇文章提到在我的应用程序中收到的此按钮上使用 BroadcastReceiver,虽然他的教程非常无用,但听起来这是朝着正确的方向发展。

Intent resultIntent = new Intent(getBaseContext(), Dashboard.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getBaseContext());
stackBuilder.addParentStack(Dashboard.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Intent cancel = new Intent(getBaseContext(), CancelNotification.class);
stackBuilder.addParentStack(Dashboard.class);
stackBuilder.addNextIntent(cancel);
PendingIntent pendingCancel =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);

NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
mb.setSmallIcon(R.drawable.cross_icon);
mb.setContentTitle(ref);
mb.setContentText(ver);
mb.setPriority(NotificationCompat.PRIORITY_LOW);
mb.setOngoing(true);
mb.setStyle(new NotificationCompat.BigTextStyle().bigText(ver));
mb.setContentIntent(resultPendingIntent);
mb.addAction(R.drawable.ic_cancel_dark, "Dismiss", pendingCancel);

manager.notify(1, mb.build());

最佳答案

从这里开始:

int final NOTIFICATION_ID = 1;

//Create an Intent for the BroadcastReceiver
Intent buttonIntent = new Intent(context, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",NOTIFICATION_ID);

//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent,0);

//Pass this PendingIntent to addAction method of Intent Builder
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
.....
.....
.....
mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
manager.notify(NOTIFICATION_ID, mb.build());

创建广播接收器:

public class ButtonReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

int notificationId = intent.getIntExtra("notificationId", 0);

// Do what you want were.
..............
..............

// if you want cancel notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}

如果您不想在用户点击通知时显示任何 Activity ,请以这种方式定义在 setContentIntent 中传递的 Intent :

PendingIntent resultPendingIntent = PendingIntent.getActivity(context,  0, new Intent(), 0);
......
......
mb.setContentIntent(resultPendingIntent);

要在单击时关闭通知托盘,请在构建通知时调用 setAutoCancel() 并设置为 true:mb.setAutoCancel(true);

关于android - 在不打开应用程序的情况下通过操作按钮关闭正在进行的 Android 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19739371/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com