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

@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

/**
     * 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

    #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,

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

    @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调试。

        @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

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

  # 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)

你可能感兴趣的:(Framework,android,framework)