Android实现Mtp访问浏览手机存储(一)访问Mtp目录 Android实现Mtp访问浏览手机存储(二) 禁止DocumentsUI文件直接弹出
当usb接入时,默认打开系统的DocumentUI。当你开发了一款文件管理器,需要增加一些适配才能响应系统的启动,首要禁止DocumentUI的默认直接弹出。
方案一
屏蔽整个DocumentUI模块,简单粗暴。缺点就是三方应用无法调起DocumentUI进行文件查找。 可以直接将DocumentUI模块的Android.mk或者Android.bp注释禁止编译。 源码目录:
/packages/apps/DocumentsUI/
方案二
去掉下面DocumentsUI源码FilesActivity中的相关启动 Action :
<activity
android:name=".files.FilesActivity"
android:documentLaunchMode="intoExisting"
android:theme="@style/DocumentsTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
<intent-filter>
<action android:name="android.provider.action.BROWSE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.document/root" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.document/root" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.document/directory" />
</intent-filter>
</activity>
方案三
在自定义的文件管理器中增加 android.intent.action.VIEW 的 Aciton 响应系统的打开请求。
<activity
android:name=".ReceiverActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:mimeType="vnd.android.document/root" />
</intent-filter>
</activity>
在系统源码目录:
Android 11以下:frameworks/base/packages/MtpDocumentsProvider/src/com/android/mtp/ReceiverActivity.java Android 11以上(含Android 11): /packages/services/Mtp/src/com/android/mtp/ReceiverActivity.java
ReceiverActivity 负责接收系统Mtp设备接入广播,从而通过 Intent.ACTION_VIEW 启动文件管理器。
public class ReceiverActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(getIntent().getAction())) {
final UsbDevice device = getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
try {
final MtpDocumentsProvider provider = MtpDocumentsProvider.getInstance();
provider.openDevice(device.getDeviceId());
final String deviceRootId = provider.getDeviceDocumentId(device.getDeviceId());
final Uri uri = DocumentsContract.buildRootUri(
MtpDocumentsProvider.AUTHORITY, deviceRootId);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Root.MIME_TYPE_ITEM);
intent.addCategory(Intent.CATEGORY_DEFAULT);
this.startActivity(intent);
} catch (IOException exception) {
Log.e(MtpDocumentsProvider.TAG, "Failed to open device", exception);
}
}
finish();
}
}
最终系统弹出下面选择框: 
|