Java – Declare the Google api key in the list (for youtube APIs)

Declare the Google api key in the list (for youtube APIs)… here is a solution to the problem.

Declare the Google api key in the list (for youtube APIs)

Using the map API, I can declare my key: in a list

<meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AlOtOfNumBersAndLetters123" />

But in the Youtube API, I have to do it programmatically (AFAIK):

String API_KEY = "AlOtOfNumBersAndLetters123";
youTubePlayerFragment.initialize(API_KEY, myOnInitializedListener);

How can I also use the key declared in the list with the Youtube API?

Solution

You can use existing metadata or define custom metadata in AndroidManifest:

<meta-data android:name="com.my.app.myYoutubeID" android:value="AlOtOfNumBersAndLetters123" />

And use it at runtime (for private or existing metadata):

String API_KEY = context.getPackageManager().getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA).metaData.getString(" com.my.app.myYoutubeID");
String API_KEY = context.getPackageManager().getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA).metaData.getString(" com.google.android.maps.v2.API_KEY"); this will use the Maps meta-data
youTubePlayerFragment.initialize(API_KEY, myOnInitializedListener);

Related Problems and Solutions