【Android】開機自啓動

要想在Android系統中實現開機啓動,很簡單,只需要幾個步驟就可以了。

1.定義廣播類

2.Manifest.xml中註冊廣播類

3.添加權限

 

下面就是具體操作了。


首先,我們來定義廣播類。

創建一個類BootReceiver,使其繼承BroadcastReceiver。

重寫一些必要的Java函數

[html] view plaincopy
  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 newIntent = 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中註冊廣播類

[html] view plaincopy
  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>  


最後,再添加上權限就可以了

[html] view plaincopy
  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>  


這樣,我們就實現了Android系統的開機自啓動,切勿忘記Manifest.xml中的操作!

 

資源有兩個,他們本質上是一樣的。程序運行後,把虛擬機或手機之類的移動設備關閉,之後重新啓動;當系統程序加載外幣後,我們的程序就會運行。

如果想隱藏,那麼只需要加上finish();就可以了。我在程序中已經添加了一個System.out,所以finish也不用擔心是否成功,只要看LogCat中是否有Successful就可以了。

有,則成功。

切記要看清時間是否吻合,以免造成不必要的麻煩!

 

Demo資源1:http://download.csdn.net/detail/etzmico/3685322

Demo資源2:http://download.csdn.net/detail/etzmico/3685327

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章