问题
I know its possible to edit a android manifest component, for example, set it enabled/disabled etc. I'd like to insert meta value tag into the application tag of the android manifest at runtime. How can i write directly into the android manifest ?
here is the string i want to write directly into my app's android manifest:
<meta-data android:name="my_api_key" android:value="mykey124" />
and it must be within the application tag.
回答1:
You can't edit the manifest at runtime.
If you need runtime solution, you should try other ways like share preference or something can save value persist.
If not just put it in manifest, take google play service for Example:
<application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
.....
</application>
回答2:
I think its late, but will help for any other searching for this answer
first Go to res > values > strings.xml and create the string resource
<string name="my_api_key">Your_api_key</string>
and After that Go to manifest file
Be sure you want to add this meta tag in your application or activity if You want to add inside the application then just start after the application tag or if activity the after the activity tag on which you want to write
<meta-data
android:name="apikey"
android:value="@string/my_api_key" />
Now finally its time to retrieve the meta data inserted in the application or the activity,
try {
ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
if (bundle != null) {
String apiKey = bundle.getString("apikey");
Log.d(this.getClass().getSimpleName(), "apiKey = " + apiKey);
}
}
} catch (PackageManager.NameNotFoundException e) {
Utilities.log(this.getClass().getSimpleName(), "Failed to load meta-data, NameNotFound: " + e.getMessage());
} catch (NullPointerException e) {
Log.e(this.getClass().getSimpleName(), "Failed to load meta-data, NullPointer: " + e.getMessage());
}
if you have put the metatag in the application then use
ApplicationInfo ai = getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
instead of Activity info , thats all.
来源:https://stackoverflow.com/questions/33577725/how-to-write-meta-data-info-to-android-manifest-at-runtime