Android 定制开机自启动应用

来源:互联网 发布:maven 指定java版本 编辑:程序博客网 时间:2024/06/05 18:53

大致思路是:写一个简单的设置应用,在里面勾选相应的应用(把相应的参数写入到sharedPreferences或者ContentProvider,根据喜好自己选择),在开机的时候读取参数,启动相对的应用;

首先新建开机监听广播,监听系统开机

package com.tcl.navigator.setting.receiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import com.tcl.navigator.setting.StartupService;public class StartupBroadcastReceiver extends BroadcastReceiver {    /**     * 开机启动广播     */    private String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";    public int startupPara;    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(BOOT_ACTION)) {            Intent intent3 = new Intent(context, StartupService.class);            context.startService(intent3);        }    }}

在启动的服务中,激活应用

package com.tcl.navigator.setting;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class StartupService extends Service {    private static String TAG = "StartupService";    /**     * 音乐     */    private static String MUSIC_ACTION = "com.tcl.navigator.action.TPMS";    /**     * 收音机     */    private static String RADIO_ACTION = "";    private static String GPS_ACTION = "";     private int curItem;    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        getData();        Intent startIntent = new Intent();        if(curItem == 1 ){            startIntent.setAction(GPS_ACTION);        }else if(curItem == 3){            startIntent.setAction(RADIO_ACTION);        }else if(curItem == 4){            startIntent.setAction(MUSIC_ACTION);        }        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         startIntent.addCategory(Intent.CATEGORY_DEFAULT);          getApplication().startActivity(startIntent);     }       /**     *读取参数     */    private void getData() {        curItem = android.provider.Settings.System.getInt(getBaseContext().getContentResolver(), "tcl_boot_start_item",0);        LogUtils.d(TAG, "get bootstart_item= "+curItem);    }}

当然激活应用也可以通过包名来启动:

Intent startIntent = new Intent();PackageManager manager = getApplication().getPackageManager();startIntent = manager.getLaunchIntentForPackage(GPS_PACKAGE);getApplication().startActivity(startIntent); 

记得在Main.xml中添加相应权限和注册相应的组件

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>        <receiver android:name=".receiver.StartupBroadcastReceiver" >            <intent-filter>                <action android:name="com.tcl.navigator.StartUpctivity" />                <action android:name="android.intent.action.BOOT_COMPLETED"/>             </intent-filter> <service android:name=".StartupService"></service>
0 0