因为项目需求要能开机启动服务,在网上看了很多,越看越糊涂.终于在下载了一个CSDN的Demo之后找到了解决办法.
先贴代码吧,首先是目录结构:
Manifest.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testbootservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
<receiver android:name=".BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
里面主要是加了一个 receiver标签和 service便签,然后加了
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
接收开机结束的广播的权限.
创建BootBroadcastReceiver类,用来处理接收到广播之后要做的事:
package com.example.testbootservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent service = new Intent(context,MyService.class);// 启动Service
context.startService(service);
}
}
因为只监听了一个action,所以就没在onReceive中判断了,直接写要做的事,这里是开启目标Service.
MainActivity.java不用修改,
创建一个MyService类:
package com.example.testbootservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(getApplicationContext(), "启动Service", Toast.LENGTH_LONG).show();
}
}
这样就OK了,我是在真机中调试的,安装到手机上后apk会自动运行一次,不用管.
此时估计你想要重启手机试试效果了,我最开始也是这么玩的,一点反应都没有,按照网上的各种说明修修改改,崩溃.
按照我说的来:
①打开"权限管理",我的是vivo手机,点击i管家里面直接就可以看到"权限管理"了
点开后默认三项都是禁止的,你要打开"自启动"和"锁屏显示"(经过我测试,这两项缺一不可),如下图
这下才算是真的大功告成了,重启玩玩.开机之后,点击"设置"->"更多设置"->"开发者选项"->"正在运行",可以看到当前正在运行的服务和进程.如下图:
开机启动程序也是一样的,只要在onReceive函数中跳转到目标活动就行了.
至于为什么非要手动设置,可能是因为开机启动这个权限太牛叉了,不能随便给,必须要用户自己主观选择给,有效避免了流氓软件的侵袭.