Can't I turn on the app when I reboot the device?

Asked 2 years ago, Updated 2 years ago, 105 views

I found the sample code, but it was so old that the classes were no longer defined. So I'm asking you a question because I don't think it's possible

android broadcastreceiver startup

2022-09-22 22:13

1 Answers

It's possible. You give a permission from the Android manifest file <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service android:name=".MyService" android:label="My Service">
    <intent-filter>
        <action android:name="com.myapp.MyService" />
    </intent-filter>
</service>

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

Register the receiver so that you can receive BOOT_COMPLETED in this way.

public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, MyService.class);
            context.startService(serviceIntent);
        }
    }
}

It also defines the receiver class that receives and processes BOOT_COMPLETED.


2022-09-22 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.