android 开机启动程序

来源:互联网 发布:可变数据喷码机报价 编辑:程序博客网 时间:2024/05/01 15:03

做一个android开机就会自动启动的程序,该程序只要启动一次,以后开机就会自动启动,直到删除该程序。

android开机事件会发送一个叫做Android.intent.action.BOOT_COMPLETED的广播信息。只要我们接收这个action并在receiver中启动我们自己的程序就可以实现了。

具体实现如下。

先建一个简单的activity:

Hello.java

[java] view plaincopy
  1. public class Hello extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.     }  
  8. }  


然后设置一个receiver接收系统发出的广播消息

StartupReceiver.java

[java] view plaincopy
  1. public class StartupReceiver extends BroadcastReceiver {  
  2.   
  3.     @Override  
  4.     public void onReceive(Context context, Intent intent) {  
  5.         // TODO Auto-generated method stub  
  6.         Intent i = new Intent(context,Hello.class);  
  7.         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  8.         //将intent以startActivity传送给操作系统  
  9.         context.startActivity(i);  
  10.   
  11.     }  
  12.   
  13. }  



然后在AndroidManifest.xml中添加


AndroidManifest.xml


[html] view plaincopy
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  2.       package="mzz.startup"  
  3.       android:versionCode="1"  
  4.       android:versionName="1.0">  
  5.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  6.         <activity android:name=".Hello"  
  7.                   android:label="@string/app_name">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN" />  
  10.                 <category android:name="android.intent.category.LAUNCHER" />  
  11.             </intent-filter>  
  12.         </activity>  
  13.         <receiver android:name=".StartupReceiver">  
  14.             <intent-filter>  
  15.                 <action android:name="android.intent.action.BOOT_COMPLETED" />  
  16.                 <category android:name="android.intent.category.HOME" />  
  17.             </intent-filter>  
  18.         </receiver>  
  19.     </application>  
  20.     <uses-sdk android:minSdkVersion="8" />  
  21.   
  22. </manifest>   

这样启动了一次该程序之后,以后开机就会自动启动该程序了。
原创粉丝点击