[置顶] 开机自启动应用的方法

最近在研究开机自启动的方法,在网上找了很多例子,最后实验成功了,今天就和大家分享下吧!

1、Manifest.xml如下。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 android:versionCode="1" android:versionName="1.0" package="cn.etzmico.autorun">


 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <receiver android:name="cn.etzmico.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>
  <activity android:name="cn.etzmico.AutoRun" android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>  设置可以接受自启动的权限。

</manifest>

2、BootReceiver.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);   //为刚要启动的Activity设置启动参数,此参数说明启动时为Activity开辟新的栈。
   /* if you want to start a service, follow below method */
   context.startActivity(newIntent);

  }
 }
}

3、AutoRun.java

package cn.etzmico;

import android.app.Activity;
import android.os.Bundle;
import cn.etzmico.autorun.R;

public class AutoRun extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  System.out.println("Successful");
 }
}

完了,就这么简单,呵呵

 

 

你可能感兴趣的:([置顶] 开机自启动应用的方法)