AKi*_*y50 3 android broadcastreceiver android-notifications notification-action
我正在开发一个项目,我需要注册 BroadcastReceiver 并从通知操作向其发送广播。如果我做错了什么明显的事情,请告诉我。我不希望接收器在清单中注册,因为我希望拥有访问多个局部变量的自定义 onRecieve 方法。
完整代码可在此处获取: https: //github.com/akirby/notificationTest
编辑: 根据Android文档(https://developer.android.com/guide/components/broadcasts.html),这是可能的,但我无法理解为什么这不起作用。
BroadcastReciever 局部变量
public BroadcastReceiver approveReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
notificationManager.cancel(notificationId);
String data = intent.getAction();
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG);
if(data != null && data.equals("com.myapp.Approve")){
mainText.setText("Approved");
}
else{
mainText.setText("Denied");
}
}
};
Run Code Online (Sandbox Code Playgroud)
登记:
registerReceiver(approveReceiver, new IntentFilter("com.myapp.Approve"));
Run Code Online (Sandbox Code Playgroud)
通知:
public void showNotification(){
Context appContext = getApplicationContext();
Intent approveIntent = new Intent(appContext, ApprovalReceiver.class);
approveIntent.setData(Uri.parse("Approve"));
approveIntent.setAction("com.myapp.Approve");
PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, approveIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Intent denyIntent = new Intent(appContext, ApprovalReceiver.class);
approveIntent.setData(Uri.parse("deny"));
denyIntent.setAction("com.myapp.Deny");
PendingIntent denyPendingIntent = PendingIntent.getBroadcast(appContext, 0, denyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test Notification")
.setContentText("Test notification details")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.ic_launcher_foreground, getString(R.string.Approved),
pendingIntent)
.addAction(R.drawable.ic_launcher_foreground, getString(R.string.Deny),
denyPendingIntent);
notificationManager.notify(notificationId, builder.build());
}
Run Code Online (Sandbox Code Playgroud)
我找到了我的问题。这与我实例化 Intent 对象和 IntentFilter 对象的方式发生冲突。IntentFilters 是通过一个操作实例化的,当我使用“.setAction”选项实例化 Intent 时,修复如下:
改变这个:
Intent approveIntent = new Intent(appContext, ApprovalReceiver.class);
Run Code Online (Sandbox Code Playgroud)
对此:
Intent approveIntent = new Intent("com.myapp.Approve");
Run Code Online (Sandbox Code Playgroud)
因为我的 BroadcastReceiver 注册的 IntentFilter 是这样的:
this.registerReceiver(approveReceiver, new IntentFilter("com.myapp.Approve"));
Run Code Online (Sandbox Code Playgroud)