Android开机自启动应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Leo_eight/article/details/49342045

Android实现开机自启动需要用到广播接收器——BroadcastReceiver。


1. 编写继承于BroadcastReceiver的类

<span style="font-size:14px;color:#ff0000;">public class LaunchReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {	
		Log.v("RECEIVER", "************onreceive**********");
	}
}</span>

2. 注册广播

<span style="font-size:14px;color:#ff0000;"><receiver android:name=".LaunchReceiver">
    <intent-filter >
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>    
</receiver></span>


3. 使用权限
<span style="font-size:14px;color:#ff0000;"><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/></span>

***但往往很多人做到以上三步后,程序还是无法自动开机启动。原因在于Android 4.0以上版本,要开机自启动,需要先打开一次该应用,才可以接收广播!


4. 打开应用

因为我们写的只是个广播,没有Activity,在手机桌面上也没有图标,那么就无法打开应用了。这时候,我们值需要新建一个Activity和一个布局界面,并注册

<span style="font-size:14px;color:#ff0000;"><activity android:name="com.leo.listen.Test">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity></span>
让这界面打开程序时就启动。此时,程序已运行过一次,之后就可把下面行代码注释掉
<span style="font-size:14px;"> <category android:name="android.intent.category.LAUNCHER" /></span>
如下:

<span style="font-size:14px;color:#ff0000;"><activity android:name="com.leo.listen.Test">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <!-- <category android:name="android.intent.category.LAUNCHER" /> -->
    </intent-filter>
</activity></span>

5. 重启手机,广播就会被触发啦!!

猜你喜欢

转载自blog.csdn.net/Leo_eight/article/details/49342045