Android实现开机自启动某个程序
jopen
11年前
使用场景:手机开机后,自动运行程序,在屏幕上显示"Hello. I started!"字样。
背景知识:当Android手机启动时,会发出一个系统广播,叫做:ACTION_BOOT_COMPLETED,它的字符串表示常量为android.intent.action.BOOT_COMPLETED。所以只要在开始时程序中捕获这个广播消息,一切就好办了。
代码如下:
1、界面代码,
package com.andy.zhu; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.app.Activity; import android.content.Intent; public class MainActivity extends Activity { private Button button_test_service; private Intent intent; private Button button_stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("hello started"); setContentView(tv); } }
2、接受广播消息,所以新建一个类,并继承BroadcastReceiver
package com.andy.zhu; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.util.Log; public class BootRestartReceiver extends BroadcastReceiver { private final String ACTION = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals(ACTION)); { Intent intent2 = new Intent(context, MainActivity.class); intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent2); Log.d("DEBUG", "开机自动服务自动启动..."); //Intent intentService = new Intent(); //intentService.setClass(context, MyService.class); //context.startService(intentService); } } }
代码都很简单。重写onReceiver方法,实现要实现的功能就行了。
3、配置menifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.andy.zhu" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:persistent="true" android:theme="@style/AppTheme" > <activity android:name="com.andy.zhu.MainActivity" 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 --> <receiver android:name="com.andy.zhu.BootRestartReceiver" > <intent-filter > <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </application> <!-- 添加权限 --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> </manifest>