Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

112.2. 配置文件

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

112.2.2. 再 AndroidManifest.xml 使用 meta-data element 定义

		
...
<application ...>
    ...
	...
    <meta-data android:name="api_url" android:value="https://api.netkiller.cn/v1/"/>
    <meta-data android:name="api_key" android:value="123456"/>
</application>		
		
		
		
public static String getMetaData(Context context, String name) {
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        return bundle.getString(name);
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Unable to load meta-data: " + e.getMessage());
    }
    return null;
}		
		
		
		
String apiUrl = getMetaData(this, "api_url");
String apiKey = getMetaData(this, "api_key");		
		
		

112.2.3. 再 build.gradle 文件中配置 productFlavors

		
productFlavors {
    prod {
        buildConfigField 'String', 'API_URL', '"https://api.netkiller.cn/v1/"'
        buildConfigField 'String', 'API_KEY', '"123456"'
    }
}
		
		

引用 config 方法

		
String apiUrl = BuildConfig.API_URL;
String apiKey = BuildConfig.API_KEY;
		
		

112.2.4. 从 assets 目录读取配置文件

		
import java.io.InputStream; 
import java.util.Properties; 
  
import android.content.Context; 
  
public class Config {
	public static Properties getProperties(Context c){ 
		Properties properties = new Properties(); 
		try { 
			//方法一:通过activity中的context攻取setting.properties的FileInputStream 
			InputStream in = c.getAssets().open("appConfig.properties"); 
	      	//方法二:通过class获取setting.properties的FileInputStream 
	      	//InputStream in = PropertiesUtill.class.getResourceAsStream("/assets/setting.properties "));  
      		properties.load(in); 
		} catch (Exception e1) { 
			e1.printStackTrace(); 
		} 
		return props; 
	}
}  		
		
		
		
Properties properties = Config.getProperties(context.getApplicationContext()); 
serverUrl = properties.getProperty("serverUrl"); 
Log.i("URL", serverUrl);
		
		

112.2.4.1. 配置文件例子

			
package cn.netkiller.album.config;

import cn.netkiller.album.MainApp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class Config {
    private static final String TAG = "Config";
    private Properties properties = null;
    public Config() {
        try {
            properties = new Properties();
            InputStream inputStream = MainApp.getContext().getAssets().open("config.properties");
            InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            properties.load(isr);
            isr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String getServerURI() {
        return properties.getProperty("mqtt.serveruri").trim();
    }

    public String getUsername() {
        return properties.getProperty("mqtt.username").trim();
    }

    public String getPassword() {
        return properties.getProperty("mqtt.password").trim();
    }

    public String getProjectName() {
        return properties.getProperty("project.name").trim();
    }

    public String getProjectScenes() {
        return properties.getProperty("project.scenes").trim();
    }

    public String getProjectGroup() {
        return properties.getProperty("project.group").trim();
    }

    public String getTopicBroadcast() {

        return properties.getProperty("mqtt.topic.broadcast").trim();
    }

    public String getTopicRegister() {
        return properties.getProperty("mqtt.topic.register").trim();
    }
    public String getTopicNotification(){
        return properties.getProperty("mqtt.topic.notification").trim();
    }
}