Android 我的 BroadcastReceiver Class 没有收到通知发送的动作
Android My BroadcastReceiver Class no receive the action send from Notification
在我的 IntentService class 中,我创建了一个 Notification 并分配了 ID=1213,一旦应用程序打开,通知就会显示。
Intent cancelScan = new Intent();
cancelScan.setAction(CANCEL);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1213, cancelScan, PendingIntent.FLAG_UPDATE_CURRENT);
mNbuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel,"Cancel Scanning",pendingIntent);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, mNbuilder.build());
在我的 BroadcastReceiver 中 class
if(CANCEL.equals(intent.getAction())){
Log.i(TAG,"Received Broadcasr Receiver");
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//context.stopService(new Intent(context,ScanService.class));
nm.cancel(NOTIFICATION_ID);
}
}
还有,我的Manifest.XML
<receiver android:name=".WifiScanReceiver" android:enabled="true">
<intent-filter>
<action android:name="CANCEL"/>
</intent-filter>
</receiver>
我尝试了几次单击通知下方的操作按钮,但 Logcat 没有打印任何内容。我做错了哪些部分?提前致谢。
清单中 CANCEL
的值和声明为操作 ("CANCEL") 的值必须相等,否则将不起作用。你没有,这就是为什么你没有达到你的 if 声明。但是你的接收器被触发了,因为你发送了一个带有正确动作的广播。
为确保您在代码中使用正确的值,您可以在 WifiScanReceiver
:
中声明一个 static final
public class WifiScanReceiver {
public static final String CANCEL = "CANCEL";
...
}
因此您也可以在发送广播时在代码中使用它:
Intent cancelScan = new Intent();
cancelScan.setAction(WifiScanReceiver.CANCEL);
这样您就可以始终确定您使用的是相同的值。您必须确保也是正确的唯一一个是清单中的那个。
在我的 IntentService class 中,我创建了一个 Notification 并分配了 ID=1213,一旦应用程序打开,通知就会显示。
Intent cancelScan = new Intent();
cancelScan.setAction(CANCEL);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1213, cancelScan, PendingIntent.FLAG_UPDATE_CURRENT);
mNbuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel,"Cancel Scanning",pendingIntent);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, mNbuilder.build());
在我的 BroadcastReceiver 中 class
if(CANCEL.equals(intent.getAction())){
Log.i(TAG,"Received Broadcasr Receiver");
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//context.stopService(new Intent(context,ScanService.class));
nm.cancel(NOTIFICATION_ID);
}
}
还有,我的Manifest.XML
<receiver android:name=".WifiScanReceiver" android:enabled="true">
<intent-filter>
<action android:name="CANCEL"/>
</intent-filter>
</receiver>
我尝试了几次单击通知下方的操作按钮,但 Logcat 没有打印任何内容。我做错了哪些部分?提前致谢。
清单中 CANCEL
的值和声明为操作 ("CANCEL") 的值必须相等,否则将不起作用。你没有,这就是为什么你没有达到你的 if 声明。但是你的接收器被触发了,因为你发送了一个带有正确动作的广播。
为确保您在代码中使用正确的值,您可以在 WifiScanReceiver
:
public class WifiScanReceiver {
public static final String CANCEL = "CANCEL";
...
}
因此您也可以在发送广播时在代码中使用它:
Intent cancelScan = new Intent();
cancelScan.setAction(WifiScanReceiver.CANCEL);
这样您就可以始终确定您使用的是相同的值。您必须确保也是正确的唯一一个是清单中的那个。