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

Android 廣播啟動 Service 失敗:onCreate 未執行的排查方向

     編輯:程式設計疑難解答

代碼中 BroadcastReceiver.onReceive 嘗試啟動 NofyService,但 Service 的 onCreate 未被調用。關鍵代碼:

Intent i = new Intent(context, NofyService.class);
i.addCategory(Intent.CATEGORY_DEFAULT); // 多餘且可能導致匹配失敗
context.startService(i);

問題分析

  • 多餘的 addCategory:顯式 Intent(指定 Component)不需要 Category,添加後可能導致 Intent 與 Manifest 中 <service> 的 <intent-filter> 不匹配,系統找不到目標 Service。
  • AndroidManifest.xml 中 Service 宣告包含 android:process 和 <intent-filter>,但顯式啟動不依賴 filter。
  • 檢查 context.startService(i) 返回值是否為 null(表示啟動失敗)。

修正建議

  1. 移除 i.addCategory(...)。
  2. 確認 Service 類名、包名與 Manifest 完全一致。
  3. 若 Service 在獨立進程(android:process),確保進程啟動權限無誤。
  4. 加上日誌:Log.d("TAG", "startService result: " + context.startService(i)); 觀察返回組件名。

顯式 Intent 啟動 Service 時,不要添加 Category,直接 new Intent(context, ServiceClass.class) 即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved