[英]Starting Android Service on Boot Time
我正在構建一個在啟動時運行的簡單服務應用程序。 問題是我希望這個應用程序只基於服務,不會有活動。 我有 BrodcastReceiever class 和服務 class 但我不知道該服務將如何在設備上運行。 我將運行配置編輯為空。 當我添加活動時,它可以工作但正如我所說,這必須只是一個服務應用程序。 為什么它不工作?
清單.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.TestService">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
<receiver android:name=".BootDeviceReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
BroadcastReceiver.java
public class BootDeviceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("testLog","broadCast started");
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Intent intentService = new Intent(context,MyService.class);
intentService.setAction(Intent.ACTION_MAIN);
intentService.addCategory(Intent.CATEGORY_LAUNCHER);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
context.startForegroundService(intentService);
}else{
context.startService(intentService);
}
}
}
}
日志未顯示在 onReceive function 中。
感謝您的幫助。
這是不可能的。 當您在設備上安裝應用程序時,您的組件都處於“停止狀態”。 在“停止狀態”時,它們不會被 Android 觸發。 為了讓您的組件脫離此 state,用戶必須手動啟動您的應用程序至少一次。 用戶啟動您的應用程序的唯一方法是啟動Activity
。 用戶啟動Activity
的唯一方法是在您的應用程序中擁有一個Activity
,並在清單中使用匹配的<activity>
聲明,其中包含 ACTION=MAIN 和 CATEGORY=LAUNCHER 的<intent-filter>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.