当前位置:   article > 正文

【Android】怎么使APP进行开机启动_android7.0 app开机启动

android7.0 app开机启动
项目需求

在Android系统开启之后,目标app可以在系统开机之后启动。

项目实现

使用广播的方式

首先我们要创建一个广播(这里是启动了一个Service服务)

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent myIntent = new Intent(context, MyForegroundService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //Android 8.0以上调用
                context.startForegroundService(myIntent);
            } else {
                context.startService(myIntent);
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

然后需要在【AndroidManifest.xml】注册清单里面
1.添加权限

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  • 1

2.注册

        <receiver
            android:name=".receiver.BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

ps:这里也可以启动一个Activity

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/890681
推荐阅读
相关标签
  

闽ICP备14008679号