如何让用户选择将应用设为默认视频播放器并在Activity中获取视频路径?
Hey there! Let's tackle your problem step by step. You want to set your app as the default video player, grab the video path in your Activity, and give users a way to choose your app as the default. I see you've already started with the intent filter in AndroidManifest.xml—great start! Let's fill in the gaps and make this work properly.
1. Perfect Your AndroidManifest.xml Configuration
First, let's fix and expand your existing intent filter. Right now it's cut off, and we need to add a few things to make sure your app shows up in the system's video player picker and handles all relevant video types. Here's the complete, corrected code:
<activity android:name=".video.NewVideoPlayerActivity" android:enabled="true" android:exported="true" android:icon="@drawable/ic_launcher"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- Allows opening videos from browsers --> <!-- Support common video formats --> <data android:mimeType="video/mp4" /> <data android:mimeType="video/mkv" /> <data android:mimeType="video/avi" /> <data android:mimeType="video/flv" /> <data android:mimeType="video/*" /> <!-- Wildcard for all video types --> </intent-filter> </activity>
- The
BROWSABLEcategory lets your app handle video links from web browsers. - Adding
video/*ensures your app recognizes all video MIME types, but you can list specific ones if you only want to support certain formats.
2. Retrieve the Video Path in Your Activity
When a user opens a video with your app, the system sends an ACTION_VIEW intent containing the video's URI. You can grab this URI in your NewVideoPlayerActivity and either get its real path (for older Android versions) or use the URI directly (recommended for Android 10+ due to Scoped Storage restrictions).
Option A: Get the Real File Path (Android 9 and below)
Use this method to convert the URI to a file path:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_video_player); Intent incomingIntent = getIntent(); if (Intent.ACTION_VIEW.equals(incomingIntent.getAction())) { Uri videoUri = incomingIntent.getData(); if (videoUri != null) { String videoPath = getRealPathFromUri(videoUri); // Use videoPath to initialize your player } } } private String getRealPathFromUri(Uri uri) { String filePath = null; if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { // Handle content URIs (from MediaStore) try (Cursor cursor = getContentResolver().query( uri, new String[]{MediaStore.Video.Media.DATA}, null, null, null)) { if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATA); filePath = cursor.getString(columnIndex); } } catch (Exception e) { e.printStackTrace(); } } else if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) { // Handle file URIs filePath = uri.getPath(); } return filePath; }
Option B: Use the URI Directly (Recommended for Android 10+)
Scoped Storage blocks direct access to file paths, so it's better to use the URI directly with a modern player like ExoPlayer:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_video_player); Intent incomingIntent = getIntent(); if (Intent.ACTION_VIEW.equals(incomingIntent.getAction())) { Uri videoUri = incomingIntent.getData(); if (videoUri != null) { // Initialize ExoPlayer SimpleExoPlayer player = new SimpleExoPlayer.Builder(this).build(); PlayerView playerView = findViewById(R.id.player_view); playerView.setPlayer(player); // Load the video using the URI MediaItem mediaItem = MediaItem.fromUri(videoUri); player.setMediaItem(mediaItem); player.prepare(); player.play(); } } }
3. Let Users Set Your App as Default
The system will automatically show a picker when multiple apps can handle video files. But if users have already set another default, you can add a button in your app to guide them to the settings page to change it:
Step 1: Add a Button to Your Layout
<Button android:id="@+id/set_default_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Set as Default Video Player" />
Step 2: Handle Button Click to Open Settings
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_video_player); Button setDefaultBtn = findViewById(R.id.set_default_btn); setDefaultBtn.setOnClickListener(v -> { // Open app details settings Intent settingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri appUri = Uri.fromParts("package", getPackageName(), null); settingsIntent.setData(appUri); startActivity(settingsIntent); }); // Check if your app is already the default if (isDefaultVideoPlayer()) { setDefaultBtn.setText("Already Default Player"); setDefaultBtn.setEnabled(false); } } // Helper method to check if your app is the default video player private boolean isDefaultVideoPlayer() { Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType("video/mp4"); ResolveInfo resolveInfo = getPackageManager().resolveActivity(testIntent, PackageManager.MATCH_DEFAULT_ONLY); return resolveInfo != null && resolveInfo.activityInfo.packageName.equals(getPackageName()); }
This way, users can easily navigate to the settings page to set your app as default, and you can even show them whether your app is already the default.
Hope these steps help you get everything working smoothly! If you run into any issues with specific Android versions or player implementations, feel free to tweak the code to fit your needs.
内容的提问来源于stack exchange,提问作者Lovish Sindhwani

