Android11编译第二弹:USB连接MTP模式+USB调试+USB信任

一、为什么需要开启USB信任和ADB调试

问题1:原始的AOSP,如果通过USB连接设备以后,会弹窗提示用户选择连接模式:MTP,大容量磁盘,照片等模式;

问题2:USB连接设备以后,需要开启USB调试模式,才方便操作adb调试;

问题3:USB设备连接以后,电脑会弹窗是否信任设备,需要点击信任当前设备,否则设备连接不成功。

使用场景:我们是自己的系统,需要支持设备USB连接,以及adb远程调试(USB调试和TCP调回),因此,系统需要默认支持USB连接,支持USB调试,默认信任连接的设备。

二、集成步骤

2.1 关闭USB调试弹窗

frameworks/base/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java

java 复制代码
@Override
    public void onCreate(Bundle icicle) {
...(省略)
/**
        final AlertController.AlertParams ap = mAlertParams;
        ap.mTitle = getString(R.string.usb_debugging_title);
        ap.mMessage = getString(R.string.usb_debugging_message, fingerprints);
        ap.mPositiveButtonText = getString(R.string.usb_debugging_allow);
        ap.mNegativeButtonText = getString(android.R.string.cancel);
        ap.mPositiveButtonListener = this;
        ap.mNegativeButtonListener = this;

        // add "always allow" checkbox
        LayoutInflater inflater = LayoutInflater.from(ap.mContext);
        View checkbox = inflater.inflate(com.android.internal.R.layout.always_use_checkbox, null);
        mAlwaysAllow = (CheckBox)checkbox.findViewById(com.android.internal.R.id.alwaysUse);
        mAlwaysAllow.setText(getString(R.string.usb_debugging_always));
        ap.mView = checkbox;
        window.setCloseOnTouchOutside(false);

        setupAlert();
	**/
	notifyService(true,true);
	finish();
}

默认只要USB连接设备,默认就开启USB调试。关键方法是notifyService

java 复制代码
/**
     * Notifies the ADB service as to whether the current ADB request should be allowed, and if
     * subsequent requests from this key should be allowed without user consent.
     *
     * @param allow whether the connection should be allowed
     * @param alwaysAllow whether subsequent requests from this key should be allowed without user
     *                    consent
     */
    private void notifyService(boolean allow, boolean alwaysAllow) {
        try {
            IBinder b = ServiceManager.getService(ADB_SERVICE);
            IAdbManager service = IAdbManager.Stub.asInterface(b);
            if (allow) {
                service.allowDebugging(alwaysAllow, mKey);
            } else {
                service.denyDebugging();
            }
            mServiceNotified = true;
        } catch (Exception e) {
            Log.e(TAG, "Unable to notify Usb service", e);
        }
    }

这个方法很简单,通过ADB服务,设置允许调试。

mKey是什么呢?就是设备指纹,即我们常说的设备SN。

2.2 授权ADB调试5555端口

device/qcom/lahaina/init.target.rc

rust 复制代码
    #Allow access to memory hotplug device attributes
    chown system system /sys/kernel/mem-offline/anon_migrate
    # ==== modify start===== zhouronghua open adb debug port 5555
    setprop service.adb.tcp.port 5555
    # ==== modify end=====

2.3 接收到USB连接默认开启USB调试

frameworks/base/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java

在其中有监听USB连接和断开的广播接收器UsbDisconnectedReceiver,

java 复制代码
private class UsbDisconnectedReceiver extends BroadcastReceiver {
...(省略)
        @Override
        public void onReceive(Context content, Intent intent) {
            String action = intent.getAction();
            if (!UsbManager.ACTION_USB_STATE.equals(action)) {
                return;
            }
            // ====== modify begin ==========
	        // fix: zhouronghua usb debug default auth
	        // boolean connected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
            boolean connected = false;
	        if (!connected) {
                Log.d(TAG, "USB disconnected, notifying service");
                // notifyService(false);
                mActivity.finish();
            }
	        // open adb debugging
	        notifyService(true, true);

	        // =========== modify end ==========
        }
    }

开启USB调试,直接开启ADB调试即可,不需要单独开启USB调试,TCP调试。

2.4 USB授权默认信息

frameworks/base/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java

java 复制代码
    @Override
    public void onCreate(Bundle icicle) {
    ...(省略)

        setupAlert();
        // ======= modify begin =========
	    // fix: zhouronghua usb default trust devices
	    Log.d(TAG, "grant usb permission automatically");
	    mPermissionGranted = true;
	    finish();
	    // ======= modify end =======

    }

默认同意授权USB连接。

2.5 USB连接默认为MTP模式

USB管理器接收到USB连接监听

frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java

USB连接默认采用MTP模式,且开启ADB调试。

java 复制代码
        @Override
        public void handleMessage(Message msg) {
        ...(省略)
            if (mBootCompleted) {
                        if (!mConnected &&            !hasMessages(MSG_ACCESSORY_MODE_ENTER_TIMEOUT)
                                && !hasMessages(MSG_FUNCTION_SWITCH_TIMEOUT)) {
                            // restore defaults when USB is disconnected
			                // fix: zhouronghua usb debug mode
			                //if (!mScreenLocked
                            //        && mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE) {
                            //    setScreenUnlockedFunctions();
                            //} else {
                                //setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
				// USB connect enable
				setEnabledFunctions(UsbManager.USB_FUNCTION_MTP, false);
				// adb enable
				setAdbEnabled(true)
                            //}
                        }
                        updateUsbFunctions();

        }

        protected void finishBoot() {
            if (mBootCompleted && mCurrentUsbFunctionsReceived && mSystemReady) {
                if (mPendingBootBroadcast) {
                        updateUsbStateBroadcastIfNeeded(getAppliedFunctions(mCurrentFunctions));
                    mPendingBootBroadcast = false;
                }
		// ========== modify start ===========
                //if (!mScreenLocked
                //        && mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE) {
                //    setScreenUnlockedFunctions();
                //} else {
                //    setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
                //}
		// fix: zhouronghua USB enable
                setEnabledFunctions(UsbManager.USB_FUNCTION_MTP, false);
		// adb enable
		setAdbEnabled(true);
		// ======== modify end =================

2.6 Release默认开启ADB调试

build/make/core/main.mk

bash 复制代码
build/make/core/main.mk

ifeq (true,$(strip $(enable_target_debugging)))
  # Target is more debuggable and adbd is on by default
  ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=1
  # Enable Dalvik lock contention logging.
  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.lockprof.threshold=500
else # !enable_target_debugging
  # Target is less debuggable and adbd is off by default
  # ==== mofify begin ===== zhouronghua fix: adb debug mode
  ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=1
  # ==== modify end ====
endif # !enable_target_debugging

在Release版本也允许进行ADB调试

2.7 post_process_props.py开启adb调试

build/make/tools/post_process_props.py

bash 复制代码
  # 1. 注释掉if prop.get("ro.debuggable") == "1"判断,Release也允许调试
  # ==== modify begin fix: zhoronghua open adb debug mode
  # if prop.get("ro.debuggable") == "1":
  # ==== modify end ====

  # 因为注释掉判断,判断体重的内容整体往前缩进
  val = prop.get("persist.sys.usb.config")
  if "adb" not in val:
    if val == "":
      val = "adb"
    else:
      val = val + ",adb"
    prop.put("persist.sys.usb.config", val)
相关推荐
CV资深专家4 小时前
Android14 SystemUI 启动流程(2)
android
怀君5 小时前
Flutter——Android原生View是如何通过Flutter进行加载
android·flutter
Kiri霧6 小时前
Kotlin方差
android·开发语言·kotlin
Kiri霧7 小时前
Kotlin泛型约束
android·linux·windows·kotlin
Kiri霧7 小时前
Kotlin内联函数
android·开发语言·微信·kotlin
liosen7 小时前
【安卓笔记】RxJava的Hook机制,整体拦截器
android·rxjava·hook
Gracker7 小时前
Android Weekly #202518
android
雨白9 小时前
通过Intent传递自定义对象的两种方式
android
Kiri霧11 小时前
Kotlin比较接口
android·java·前端·微信·kotlin
阿华的代码王国11 小时前
【Android】EditText使用和监听
android·xml·java