是否可以在本机中访问Android的共享首选项?例如,如果我创建一个
SharedPreferences sharedpreferences = getSharedPreferences("somePreference", Context.MODE_ENABLE_WRITE_AHEAD_LOGGING);
如何在本机中访问密钥?
答案 0 :(得分:1)
您可以这样做:
在Handler类中,您可以创建构造函数和init方法,以将此上下文提供给ReactNatives的应用程序上下文。
private static Handler handler;
public Handler(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);
}
public static void init(Context context) {
handler = new Handler(context);
}
//Getting keys to the React native
public Map<String, ?> getAllSharedData(){
return sharedpreferences.getAll();
}
在提供数据的类(ProvideData)中,您可以执行某些操作
public static String[] getAllKeys() {
Map<String, ?> keyValues = Handler.getInstance().getAllSharedData();
List<String> keys = new ArrayList<>(keyValues.keySet());
String[] results = new String[keys.size()];
for (int i = 0; i < keys.size(); i++) {
results[i] = keys.get(i);
}
return results;
}
最后在RNSharedPreference中获取密钥( getReactApplicationContext())
@ReactMethod
public void getAllKeys(Callback successCallback){
Handler.init(getReactApplicationContext());
String[] keys = ProvideData.getAllKeys();
WritableNativeArray data = new WritableNativeArray();
for(int i=0; i<keys.length; i++){
data.pushString(keys[i]);
}
successCallback.invoke(data);
}