標籤:
在Android中讀取設定檔,可以使用System.getProperties()方法讀取:
1,在res資來源目錄下,建立一個檔案夾 raw,然後在其下建立一個.properties檔案.如:
request_char=utf-8URL=http://192.168.1.101:8080/ServerAQI/JsonActionrange_long=7#daysfrom_date_name=fromDateto_date_name=toDate
2,可以定義一個工具類,接受android.content.res.Resources類型的參數,返回Properties對象,如:
package spt.assist;import java.io.IOException;import java.util.Properties;import android.content.res.Resources.NotFoundException;import android.util.Log;import spt.aqi.activity.R;public class PropertyConfig {/**擷取設定檔資訊中的指定值. * @param resources * @param key * @return */public static String getProperty(android.content.res.Resources resources,String key) {Properties properties = getProperties(resources);return properties.getProperty(key);}/**擷取設定檔中的資訊. * @param resources * @return */public static Properties getProperties(android.content.res.Resources resources) {Properties props = new Properties();try {props.load(resources.openRawResource(R.raw.properties));} catch (NotFoundException e) {Log.i("sysout","ResourceSearcher:OpenFileFromUtil:" + e.getMessage());e.printStackTrace();return null;} catch (IOException e) {Log.i("sysout","ResourceSearcher:OpenFileFromUtil:" + e.getMessage());e.printStackTrace();return null;}return props;}}
3,在Android中的資源類ContextWrapper的子類(如Activity或Service)類中調用調用getResources()方法並傳入上面的工具類的方法,如,在Service類中,
final String url = PropertyConfig.getProperty(getResources(), "URL");
Android - 讀取Properties設定檔