首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android BroadcastReceiver 中發送廣播與啟動服務的正確姿勢:上下文選擇與 Intent 構建

     編輯:程式設計疑難解答

常見錯誤

在 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 內)。
  • 每個 Intent 明確設置 action,避免隱式匹配失效。
  • Android 8.0+ 隱式廣播限制:需動態註冊或使用顯式 Intent / JobScheduler 替代。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved