I'm building a simple service app which runs on boot time. The problem is I want this application is only based on service, there will be no activity. I have BrodcastReceiever class and Service class but I couldn't figure how this service will work on device. I edit the run configuration as nothing. When i add activity it works But as i said this must be just a service application. Why it is not working?
manifest.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);
}
}
}
}
The log doesn't show up in onReceive function.
Thanks for any helps.
This is not possible. When you install your app on a device, your components are all in the "stopped state". They will not be triggered by Android while in the "stopped state". In order to get your components out of this state, the user must, manually, start your app at least once. The only way for the user to start your app is to launch an Activity
. And the only way for the user to launch an Activity
is for you to have an Activity
in your app, and a matching <activity>
declaration in your manifest, with an <intent-filter>
containing ACTION=MAIN and CATEGORY=LAUNCHER.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.