简体   繁体   中英

Android start system service at app startup

In the AndroidManifest.xml I register a BroadcastReceiver to the "android.intent.action.BOOT_COMPLETED" event. This starts the service each time the Android device boots.

...
        <receiver android:name="MySystemScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
...

However, I'd like the system service to be started right after app installation without the need to reboot the device.

Is there a system event that I could use when the app starts? Or do I need to set a custom event?

Should I modify my manifest file to something like

...
        <receiver android:name="MySystemScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="com.myapp.StartSysService" />
            </intent-filter>
        </receiver>
...

and then launch the service from my main activity with something like

...
        Intent intent = new Intent();
        intent.setAction("com.myapp.StartSysService");
        sendBroadcast(intent);
...

If so, which method should I use? (onCreate, onResume...)

Thanks

You can subclass the Application, which has an onCreate() callback. You can start your service there.

public class MyApplication extends Application {
    public void onCreate() {
        // start your service
    }
}

In the <application> tag of your manifest, add android:name="MyApplication"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM