【Android】開機自啟動 .

來源:互聯網
上載者:User

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

1.定義廣播類

2.Manifest.xml中註冊廣播類

3.添加許可權

 

 

下面就是具體操作了。

 

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

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

重寫一些必要的Java函數

package cn.etzmico;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootReceiver extends BroadcastReceiver {
 public void onReceive(Context context, Intent intent) {

  if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
   Log.d("BootReceiver", "system boot completed");

   // context, AutoRun.class
   Intent newIntent = new Intent(context, AutoRun.class);

   /* MyActivity action defined in AndroidManifest.xml */
   newIntent.setAction("android.intent.action.MAIN");

   /* MyActivity category defined in AndroidManifest.xml */
   newIntent.addCategory("android.intent.category.LAUNCHER");

   /*
    * If activity is not launched in Activity environment, this flag is
    * mandatory to set
    */
   newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

   /* if you want to start a service, follow below method */
   context.startActivity(newIntent);

  }
 }
}

AutoRun.class就是程式啟動並執行Activity。

其次,在Manifest.xml中註冊廣播類

<receiver android:name=".BootReceiver" android:label="@string/app_name">
 <intent-filter>
  <action android:name="android.intent.action.BOOT_COMPLETED" />
  <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
</receiver>

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

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

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

 

 

資源有兩個,他們本質上是一樣的。程式運行後,把虛擬機器或手機之類的行動裝置關閉,之後重新啟動;當系統程式載入外幣後,我們的程式就會運行。

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

有,則成功。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.