Android 11 / API 30 - Open YouTube link

Viewed 3462

I currently struggle to have YouTube links to be opened in the browser or the YouTube app. I am aware of the new Package visibility in Android 11 and implemented it this way.

MyClass.java$myMethod

String ytLink = "https://www.youtube.com/watch?v=Hp_Eg8NMfT0"
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ytLink)); 
if (intent.resolveActivity(context.getPackageManager()) != null) {  
  context.startActivity(intent); 
}

AndroidManifest.xml

<manifest>
  <queries>
    <intent>
      <action android:name="android.intent.action.VIEW" />
      <data android:scheme="https" />
    </intent>
  </queries> 
</manifest>

However the intent.resolveActivity returns null... Every other link I've tried returns a ComponentName so the Intent can be started... Do you have any clue?

Thanks in advance ;)

3 Answers

Yet another option would be to add the host to the queries list in the manifest:

<queries>    
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data  android:scheme="https" android:host="youtube.com" />
    </intent>
</queries>

It seems that the simple approach with just the scheme fails as the Youtube app not only filters for the scheme of the request but (for obvious reasons) also for the specific host.

BTW: When I tested, both "youtube.com" and "youtu.be" worked equally on both kinds of links. I still threw in both in my app to be safe.

You also need to put action and data to intent-filter of Activity in Manifests

Such as

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />

    <data android:scheme="https" />
</intent-filter>

You can check the docs here

The solution was to add a category CATEGORY_BROWSABLE to the Intent to allow the browser to be one of the app to handle the YouTube URL. You could also play with the flags FLAG_ACTIVITY_REQUIRE_NON_BROWSER and FLAG_ACTIVITY_REQUIRE_DEFAULT as described in the documentation to open it in the YouTube app also but my main issue was that no activity was found so open in browser was an option ;)

Related