我正在做一个项目,我需要注册一个 BroadcastReceiver 并从通知操作向它发送广播。请告诉我是否有明显的地方我做错了。我不希望接收者在清单中注册,因为我想要访问多个局部变量的自定义 onRecieve 方法。
此处提供完整代码:https ://github.com/akirby/notificationTest
编辑: 根据 Android 文档(https://developer.android.com/guide/components/broadcasts.html),这是可能的,但我无法理解为什么这不起作用。
广播接收器局部变量
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");
}
}
};
登记:
registerReceiver(approveReceiver, new IntentFilter("com.myapp.Approve"));
通知:
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());
}