前言
上一篇文章如何实现无界面Android app介绍了如何使app仅在后台运行服务,而这样的app常常需要同时具备开机自启动的功能,接下来讲解一下如何在上一篇文章基础上,再实现app开机自启动功能。
代码实现
AndroidManifest.xml
为了实现开机自启动功能,app需要监听android开机广播,AndroidManifest.xml中需要添加以下权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
然后注册接收系统开机广播消息的广播接收者:
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
完整代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bootserviceapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:theme="@android:style/Theme.NoDisplay"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"></service>
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
BootReceiver.java
编写广播接收者代码,广播接收者在收到android开机广播后,启动MainActivity(安卓8.0以上直接启动service无法正常运行,需要先启动activity,在activity里启动service):
package com.example.bootserviceapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
public BootReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Jason", "BootReceiver start");
//启动MainActivity
Intent intent1 = new Intent(context, MainActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//添加标记
context.startActivity(intent1);
Log.v("Jason", "BootReceiver end");
}
}
MainActivity.java、MyService.java
MainActivity.java和MyService.java的示例代码参考上一篇文章如何实现无界面Android app即可。
问题解决
如果app自启动失败,可以尝试以下方法进行解决:
1、确认手机管家是否禁止了app自启动,如果被禁用,在手机管家中为app添加自启动权限后,再进行尝试:
2、如果app安装在SD卡中,可能会导致接收不到系统的广播消息,这种情况可以在AndroidManifest.xml中添加如下代码,使app只能被安装在内存中:
android:installLocation="internalOnly"