Android中实现开机自动启动服务(service)实例

2019-12-10 20:02:11刘景俊

import android.content.Context;
import android.content.Intent;

public class ServiceReceiver extends BroadcastReceiver {

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

 


AndroidManifest.xml

最后,要在 Manifest 中注册 Service 和 Receiver,增加上访问 Internet 和 Boot completed 的权限。

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://www.easck.com/apk/res/android"
          package="hev.socks5"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:label="@string/app_name" >
                <service android:name=".MainService">
                        <intent-filter>
                                <action android:name="hev.socks5.MainService" />
                        </intent-filter>
                </service>
                <receiver android:enabled="true" android:name=".ServiceReceiver">
                        <intent-filter>