Android: Retrieving shared preferences of other application

前端 未结 6 2118
迷失自我
迷失自我 2020-11-22 15:21

I have a settings application from which i have to retrieve other applications preferences, but i don\'t have the details of keys in them, how can i retrieve all the availab

6条回答
  •  星月不相逢
    2020-11-22 16:11

    It's simple to retrieve store shared preferences data of one application to another application.

    Step 1: add the same android:sharedUserId="android.uid.shared" in both app's manifest files.

    Step 2: Store Value application1

     SharedPreferences preferences = context.getSharedPreferences("token_id",    Context.MODE_WORLD_READABLE);
            Editor editor = preferences.edit();
            editor.putString("shared_token", encryptedValue);
            Log.e("aaa *** shared_token : ", encryptedValue.toString());
            editor.commit();
    

    Step 3: Get Value From application2

    Context con = null;
            try {
                con = createPackageContext("application2 package name", Context.CONTEXT_IGNORE_SECURITY);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
    
            try {
                if (con != null) {
                    SharedPreferences pref = con.getSharedPreferences(
                            "token_id", Context.MODE_WORLD_READABLE);
    
                    String data = pref.getString("shared_token", "");
                    Log.d("msg", "Other App Data: " + data);
                } else {
                    Log.d("msg", "Other App Data: Context null");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    

提交回复
热议问题