Android开机自启动


要想在Android系统中实现开机启动,很简单,只需要几个步骤就可以了。

1.定义广播类

2.Manifest.xml中注册广播类

3.添加权限

下面就是具体操作了。

首先,我们来定义广播类。

创建一个类BootReceiver,使其继承BroadcastReceiver。

重写一些必要的Java函数

  1. package cn.etzmico;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7.   
  8. public class BootReceiver extends BroadcastReceiver {  
  9.     public void onReceive(Context context, Intent intent) {  
  10.   
  11.         if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {  
  12.             Log.d("BootReceiver", "system boot completed");  
  13.   
  14.             // context, AutoRun.class  
  15.             Intent newnewIntent = new Intent(context, AutoRun.class);  
  16.   
  17.             /* MyActivity action defined in AndroidManifest.xml */  
  18.             newIntent.setAction("android.intent.action.MAIN");  
  19.   
  20.             /* MyActivity category defined in AndroidManifest.xml */  
  21.             newIntent.addCategory("android.intent.category.LAUNCHER");  
  22.   
  23.             /*  
  24.              * If activity is not launched in Activity environment, this flag is  
  25.              * mandatory to set  
  26.              */  
  27.             newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  28.   
  29.             /* if you want to start a service, follow below method */  
  30.             context.startActivity(newIntent);  
  31.   
  32.         }  
  33.     }  
  34. }  

AutoRun.class就是程序运行的Activity。

其次,在Manifest.xml中注册广播类

  1. <receiver android:name=".BootReceiver" android:label="@string/app_name">  
  2.     <intent-filter>  
  3.         <action android:name="android.intent.action.BOOT_COMPLETED" />  
  4.         <category android:name="android.intent.category.LAUNCHER" />  
  5.     </intent-filter>  
  6. </receiver>  

最后,再添加上权限就可以了

  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>  

这样,我们就实现了Android系统的开机自启动,切勿忘记Manifest.xml中的操作!

本文Android开机自启动 工程资源下载:

免费下载地址在 http://linux.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /pub/Android源码集锦/2011年/10月/Android开机自启动/

相关内容