更新时间:2022-05-28 21:50:33
首先,你需要在允许你的的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.