Android設定加密鎖屏不可訪問MTP

黃燜雞米花發表於2018-06-17

USB計算機連線方式

android裝置通過資料線連線到PC,通常有四種連線方式可選。

Android設定加密鎖屏不可訪問MTP
之前已經修改過預設連線方式為MTP,在此基礎上,要求在加密鎖屏時不可訪問MTP,解鎖後可以訪問。

實現

MtpService.java

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        UserHandle user = new UserHandle(ActivityManager.getCurrentUser());
        synchronized (this) {
            mVolumeMap = new HashMap<>();
            mStorageMap = new HashMap<>();
            mStorageManager.registerListener(mStorageEventListener);
            //++註冊廣播監聽鎖屏狀態
            registerReceiver(userUnlockReceiver, new IntentFilter(Intent.ACTION_USER_PRESENT));
            //++
            mVolumes = StorageManager.getVolumeList(user.getIdentifier(), 0);
            for (StorageVolume volume : mVolumes) {
                if (Environment.MEDIA_MOUNTED.equals(volume.getState())) {
                    volumeMountedLocked(volume.getPath());
                } else {
                    Log.e(TAG, "StorageVolume not mounted " + volume.getPath());
                }
            }
        }
複製程式碼
private void updateDisabledStateLocked() {
        //判斷鎖屏狀態,當加密鎖屏未解鎖時,返回true
        KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        mMtpDisabled = mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
        //mMtpDisabled = !mUnlocked;
    
        if (LOGD) {
            Log.d(TAG, "updating state; mMtpLocked=" + mMtpDisabled);
        }
    }
複製程式碼

    private final BroadcastReceiver userUnlockReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (mBinder){
                            if(mMtpDisabled){ //此時螢幕已解鎖,若上次MTP狀態為LOCKED,則開啟mtp
                                addStorageDevicesLocked();
                                mMtpDisabled = false;
                            }
                        }
                    }
                },"addStorageDevices").start();
            }
        }
    };

複製程式碼

相關文章