首页 > 代码库 > Android 广播(Broadcast)程序开机自启动

Android 广播(Broadcast)程序开机自启动

学习这个“通过广播开机自启动”知识点时忽略了手机本身“设置”里面自启动权限的没有打开,害得我思考好久。

技术分享

BootTestActivity.class

package com.xxx.study;import android.os.Bundle;import android.app.Activity;import android.view.Menu;public class BootTestActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);    }    }

 

BootCompletedReceiver.class

package com.xxx.study;  import android.R.anim;import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.AndroidCharacter; public class BootCompletedReceiver extends BroadcastReceiver {   @Override   public void onReceive(Context context, Intent intent) {         System.out.println("@@@@@@");            if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))     {         System.out.println("@@@@@@...bootComplete!");      Intent newIntent = new Intent(context, BootTestActivity.class);       newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  //注意,必须添加这个标记,否则启动会失败       context.startActivity(newIntent);            }         } } 
manifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.xxx.study"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" /> <!-- permissions -->     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />     <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.xxx.study.BootTestActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>          <!-- receivers -->         <receiver android:name=".BootCompletedReceiver">             <intent-filter>                 <action android:name="android.intent.action.BOOT_COMPLETED" />                  <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>         </receiver>     </application></manifest>

 

Android 广播(Broadcast)程序开机自启动