Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

第 34 章 配置檔案

目錄

34.1. *.properties 檔案
34.2. 再 AndroidManifest.xml 使用 meta-data element 定義
34.3. 再 build.gradle 檔案中配置 productFlavors

34.1. *.properties 檔案

創建 properties 檔案 res/config/development.properties

		
api_url=https://api.netkiller.cn/v1/
api_key=123456		
		
		
		
package cn.netkiller.app;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class Config {
    private static final String TAG = "Config";

    public static String getKey(Context context, String name) {
        Resources resources = context.getResources();

        try {
            InputStream rawResource = resources.openRawResource(R.config.development);
            Properties properties = new Properties();
            properties.load(rawResource);
            return properties.getProperty(name);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Unable to find the config file: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "Failed to open config file.");
        }

        return null;
    }
}		
		
		
		
String apiUrl = Config.getKey(this, "api_url");
String apiKey = Config.getKey(this, "api_key");