Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 知乎專欄 | Search | About

第 3 章 配置檔案

目錄

3.1. *.properties 檔案
3.2. 再 AndroidManifest.xml 使用 meta-data element 定義
3.3. 再 build.gradle 檔案中配置 productFlavors

3.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");