android - 我怎么知道在通知中点击了哪个按钮?
问题描述
每个通知中都有三个按钮(主通知按钮、计时器按钮和禁用按钮)。
- 主通知按钮运行前台服务
- 计时器按钮运行前台服务,但显示toast 消息
- 禁用按钮从状态栏中删除通知
有没有办法为所有三个按钮使用一个前台服务?如果是这样,我如何确定在服务中单击了哪个按钮?或者我必须为每个按钮创建三个前台服务?
我的代码
PendingIntent pendingIntentMain = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("main", "a"), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentTimer = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("timer", "b"), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentDisable = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("disable", "c"), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, String.valueOf(NOTIFICATION_ID))
.addAction(R.mipmap.ic_launcher, context.getString(R.string.timer), pendingIntentTimer)
.addAction(R.mipmap.ic_launcher, context.getString(R.string.disable), pendingIntentDisable)
.setContentIntent(pendingIntentMain)
.setOngoing(true)
.setAutoCancel(false)
.setShowWhen(false)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.tap_to_enable_service))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
前台服务
public class ForegroundService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("ABC", "" + intent.getStringExtra("main"));
Log.w("ABC", "" + intent.getStringExtra("timer"));
Log.w("ABC", "" + intent.getStringExtra("disable"));
Log.w("ABC", "" + intent.getExtras());
return super.onStartCommand(intent, flags, startId);
}
}
里面什么都Log.w
没有onStartCommand
解决方案
无需创建不同的前台服务,您可以使用 Intent Action 而不是将 Intent 与数据一起传递。喜欢,
Intent intent = new Intent(this , ClipTextObserverService.class);
intent.setAction("specify_name_of_the_action")
PendingIntent.getService(
this,
1464,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
相应地更改标志。在 addAction() 方法中传递这个 pendingIntent。然后检查 Service.Like 的 onStartCommand() 方法中的操作,
@Override
public int onStartCommand(Intent Intent , Int flags , Int startId) {
switch (intent.getAction()) {
case "your_action_name":
// TODO == Perform your action here.
break;
}
return super.onStartCommand(intent, flags , startId);
}
推荐阅读
- python - 完整性错误,创建新游戏实例时限制非空常量
- ios - 将模拟的 UIView 添加到视图层次结构
- php - 如何使用 Laravel 在控制器中显示视图
- angular - 尝试在我的自定义主题中导入角度材质主题文件,但找不到该文件
- ios - 在第二个动画之前查看跳转
- mysql - 如何修复“java.sql.SQLException:无法添加外键约束”。创建具有双主/外键关系的表时
- android - 如何支持 18.5:9 的宽高比?
- php - 如何在我的模态中显示来自 foreach 的数据?
- php - 基于关系 Laravel 5.8 和 Eloquent 更新数据库表
- c++ - 从 http 流(在 boost::beast 中)读取和写入的要求是什么?