且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在启动时启动我的应用程序?

更新时间:2022-11-25 16:05:55

首先,您需要AndroidManifest.xml中的许可权:

First, you need the permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

此外,在您的AndroidManifest.xml中,定义您的服务并收听 BOOT_COMPLETED 操作:

Also, in yourAndroidManifest.xml, define your service and listen for the BOOT_COMPLETED action:

<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>

然后,您需要定义将执行 BOOT_COMPLETED 操作并启动服务的接收器.

Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.

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);
        }
    }
}

现在,当手机启动时,您的服务应已运行.

And now your service should be running when the phone starts up.