USB计算机连接方式
android设备通过数据线连接到PC,通常有四种连接方式可选。
实现
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();
}
}
};
复制代码