Android 实现开机自启+aidl

添加权限AndroidManifest.xml中添加权限如下图

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <!--8.0以上开启服务添加权限-->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />a

注册一个BroadcastReceiver来检测android系统开机时发出的开机广播: 开机自启动广播接受

package com.example.appservices;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

/**
 * @author yuminsi
 * @description
 * @date 2021/7/24 15:30
 * @since 注册一个BroadcastReceiver来检测android系统开机时发出的开机广播: 开机自启动广播接受
 */
public class AutoStartBroadcastReceiver extends BroadcastReceiver {
    private String TAG = "AutoStartBroadcastReceiver";
    static final String action_boot = "android.intent.action.BOOT_COMPLETED";
    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        if (intentAction.equals(action_boot)) {
            Intent startIntent = new Intent(context, MainActivity.class);
            //addFlags非常重要,如果缺少的话,程序将在启动的时候报错
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //自启动APP(Activity)
             Log.e(TAG, "start activity = " );
             context.startActivity(startIntent)Intent service = new Intent(context, MyService.class);
            //自启动服务(Service)
            Log.e(TAG, "start SERVICE = ");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //8.0以上系统开启服务,注意在使用startForegroundService开启服务后需要在服务类中的onCreate中或者是  	onStartCommand中添加startForeground();
                context.startForegroundService(service);
            } else {
                context.startService(service);
            }
        }
    }
}

在AndroidManifest.xml中的application中添加广播注册

<!--开机自启动广播接受-->
        <receiver
            android:name=".AutoStartBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <!--广播优先级的设置-->
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </receiver>

添加aidl,在项目的main文件夹下右键点击选择new-》aidl

在这里插入图片描述
创建完成后会在你的main文件夹下看到一个aidl文件夹,文件夹下面有一个刚才创建的aidl接口文件
在这里插入图片描述
在.aidl接口文件中添加自己的接口
在这里插入图片描述

创建开启自己的activity或者service,这里以service为例

package com.example.appservices;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.demo.mylibrary.HengdaManager;
import com.demo.mylibrary.bean.TransInfo;
import com.demo.mylibrary.callback.BleListenerCallback;
import com.demo.mylibrary.callback.TransInfoCallback;
import com.example.appservices.callback.IMyAidlCallBack;
import com.example.bleserversdk.log.AndroidConsoleLogPrinter;

import java.text.DecimalFormat;

public class MyService extends Service {
     private String TAG = "MyService";
    private static final String NOTIFICATION_ID = "com.example.appservices";
    private static final String NOTIFICATION_NAME = "message";

    public MyService() {
        Log.e(TAG, "启动了!--MyService");
    }


    /**
     * 在整个生命周期中仅调用一次,进行一些初始化工作
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate");
        //8.0系统需要在开启服务后五秒内调用否则程序会出现ANR
        goForeground();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }


 
    /**
     * 解决8.0以上系统启动服务
     */
    private void goForeground() {
        AndroidConsoleLogPrinter.d(TAG, "goForegroud");
        //创建NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(this);
            NotificationManager notificationManager = (NotificationManager)
            getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId(NOTIFICATION_ID);
            Notification notification = builder.build();
            startForeground(1, notification);
        }

    }
  
    /**
     * 当其他组件调用bindService()方法时,该方法会被调用(如果不想让这个service被绑定,在此返回null即可)
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }

//实现aidl文件中的接口
    private class MyBinder extends IMyAidlInterface.Stub {

        @Override
        public void startBle(IMyAidlCallBack callBack) {
            Log.e(TAG, "开启蓝牙服务");
           
        }

        @Override
        public void closeBle(IMyAidlCallBack callBack) {
            Log.e(TAG, "关闭蓝牙服务");
           
        }
    }
}

注意:
1.如果遇到 Bad notification for startForeground问题请参考添加链接描述
2.如果遇到8.0以上系统无法开机自启
2.1:确认手机是否禁止了app自启动,如果被禁用,在手机中为app添加自启动权限
在手机中找到“应用启动管理”然后在里面找到需要自启动的app
在这里插入图片描述
2.2检查手机是否设置了app安装首选位置是sd卡那么直接在AndroidManifest.xml文件中添加android:installLocation=“internalOnly

manifest
  	 xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.appservices"
    android:installLocation="internalOnly">

3.安装完程序后先手动开启一下程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

甜美冰景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值