Android 开机自启动程序的实现

Android在开机启动完成后,会发送一个action为android.intent.action.BOOT_COMPLETED的广播,因此,要实现程序开机启动,只要监听这个广播即可。
先写个广播接收器:


package com.pocketdigi.com;

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

public class Receiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Intent it=new Intent(context,AutoRunActivity.class);
		it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(it);
		//貌似程序在没有运行时,必须加Intent.FLAG_ACTIVITY_NEW_TASK
	}

}

然后在AndroidManifest.xml中注册接收器,并且加上intent-filter


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pocketdigi.com"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AutoRunActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".Receiver">
        	<intent-filter>
        		<action android:name="android.intent.action.BOOT_COMPLETED"></action>
        		<category android:name="android.intent.category.HOME"></category>
        	</intent-filter>
        </receiver>
    </application>
</manifest>

OK,就这么简单,试试吧

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记