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