如題,有時候兩隻應用程式需要讀取各別設定的資料來源時可以使用
package com.android.demo.sps;
import com.android.demo.sps.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
public class DemoSavePreference extends Activity {
private static final String PREF = "DemoSavePreference_PREF";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = this.getSharedPreferences(PREF, MODE_WORLD_READABLE);
settings.edit().putString("info", "XXXXXXXXXXXXXX").commit();
}
}
MODE_WORLD_READABLE:是允許其它應用程式能讀取建立的偏好設定檔
package com.camangi.android.spg;
import com.camangi.android.spg.R;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DemoGetSavePreference extends Activity {
private static final String PREF = "DemoSavePreference_PREF";
private static final String TAG = "DemoGetSavePreference";
TextView info;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
info = (TextView) findViewById(R.id.info);
Context myContext = null;
try {
myContext = createPackageContext("com.android.demo.sps", 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
Log.d(TAG, "createPackageContext error: "+e.getMessage());
e.printStackTrace();
}
SharedPreferences testPrefs = myContext.getSharedPreferences(PREF, MODE_WORLD_READABLE);
String result = testPrefs.getString("info", "null");
info.setText(result);
}
}
讀取別的應用程式資料來源的方法,先利用createPackageContext 取得別的應用程式的Context物件,再呼叫Context 類別的getSharedPreferences來取得偏好設定,或是利用openFileInput 或openFileOutput方法來取得檔案。
最後提醒大家如果是已建好的SharePreferences檔案,使用MODE_WORLD_READABLE時,必須先把檔案給刪除後,才可以分享給別的應用程式使用,若不想刪除此檔,可以另建一個分享的SharePreferences檔案
留言列表