在 onReceive 中直接 sendBroadcast(intent) 但未指定 action,或用 context.startService(intent) 卻傳遞了錯誤的 intent 變量(示例中 intent 被覆蓋)。
public class NetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
boolean wifi = info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
if (wifi) {
Intent svc = new Intent(context, MyService.class);
context.startService(svc);
} else {
Intent bc = new Intent();
bc.setAction("com.myapp.NETWORK_CHANGED");
bc.putExtra("wifi", false);
context.sendBroadcast(bc);
}
}
}context.sendBroadcast() 而非 sendBroadcast()(後者需在 Activity/Service 內)。action,避免隱式匹配失效。