Android如何实现程序自启动

1.首先我们需要创建一个广播接收者,自定义一个类去继承BroadcastReceiver,然后重写onReceive()方法,在其中启动你要启动的app或者service,例如;

public class SelfStarting extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, SelfStarting.class);
        context.startService(service);
        Log.d("chg","开机自启动成功!");
        //启动应用,参数为需要自动启动的应用的包名
       Intent launchIntentForPackage = context.getPackageManager()
        .getLaunchIntentForPackage("com.example.johncheng.appselfstarting");
        context.startActivity(launchIntentForPackage);
      //当应用安装在SD中时需要添加如下代码:         
   if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED) || 
       intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED))  
    {  
    Intent launchIntent = new Intent(context, Login_Activity.class);  
    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    context.startActivity(launchIntent);
 }
}

2.在清单文件中配置我们的广播,

<receiver android:name=".SelfStarting">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>

    //当应用安装在SD卡时,需要添加如下action,记住:需要单独放在intent_filter中,否则
      BOOT_COMPLETED无法监听到 
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_MOUNTED"/>
        <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
    </intent-filter>

 </receiver>

3.添加相应的权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
这样就完成了应用的开机自启动。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值