Android创建自定义Application

开发目的

  1. 创建一个自定义的MainApplication继承Application。
  2. 读取AndroidManifest.xml文件中Application节点的META-DATA数据。此处以ApiKey为假想数据。

实现代码

MainApplication.java文件

package com.irisleon.application;

import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

public class MainApplication extends Application {
    private static final String TAG = "MainApplication";
    private static String mApiKey = null;

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            // 获得Application节点的META-DATA信息
            ApplicationInfo info = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            mApiKey = info.metaData.getString("ApiKey");
            if (mApiKey == null || "".equals(mApiKey)) {
                Log.e(TAG, "Can NOT find value of ApiKey in Manifest.xml!");
            }
            else {
                Log.i(TAG, "ApiKey Loaded!");
            }
        }
        catch (PackageManager.NameNotFoundException exception) {
            Log.e(TAG, "Can NOT find value of ApiKey in Manifest.xml!");
        }
    }

    public static String getApiKey() {
        if (mApiKey == null) {
            mApiKey = "";
        }
        return mApiKey;
    }
}

AndroidManifest.xml文件

增加android:name属性,设定为MainApplication的类名

<application
	android:name="com.irisleon.application.MainApplication"
	android:allowBackup="true"
	android:icon="@mipmap/ic_launcher"
	android:label="@string/app_name"
	android:roundIcon="@mipmap/ic_launcher_round"
	android:supportsRtl="true"
	android:theme="@style/Theme.SmartCore">
	<activity android:name="com.irisleon.activity.SettingActivity"></activity>
	<activity android:name="com.irisleon.activity.MainActivity">
		<intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
		</intent-filter>
	</activity>
	<meta-data android:name="ApiKey" android:value="ABCABCDEFDEF"></meta-data>
</application>

Android创建自定义Application

上一篇:微信开启全民付费模式,我们有个共同好友叫“Feed广告”


下一篇:微信赚钱:10万100万1000万级利润玩法尽在此