其他分享
首页 > 其他分享> > Android创建自定义Application

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>

标签:MainApplication,ApiKey,Log,自定义,Application,Android,mApiKey,android
来源: https://www.cnblogs.com/smartcore/p/14638201.html