2
0

やりたいこと

アプリ間でデータの共有を行いたい
片方のアプリがプロセスKillされている状態でもデータの参照を行えるようにしたい

以前、非推奨のSharedUserIDを使って実現したが、推奨、かつ簡単に行える実装(SystemProperties)をみつけたので備忘録

Step1.SystemPropertiesとは

Androidのデバイス動作や設定を制御するキーと値のペアが格納されているもの。

ADBコマンド例

# デバイスのモデル名をシステムプロパティから取得する
adb shell getprop ro.product.model

Step2.実装方法

SystemPropertiesへの書き込み

任意のキーを指定して、値を書き込む

public void writeSystemProperties(String key, String val) {
    try {
        @SuppressLint("PrivateApi")
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");

        @SuppressWarnings("rawtypes")
        Class[] paramTypes = {String.class, String.class};
        Method set = SystemProperties.getMethod("set", paramTypes);

        Object[] params = {key, val};
        set.invoke(SystemProperties, params);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // hoge.fugaというキーで、testtestを書き込む
    writeSystemProperties("hoge.fuga", "testtest");
}

SystemPropertiesの読み込み

任意のキーを指定して、値を読み込む
Android標準のキーを指定して読み込むことも可

public String readSystemProperties(String key) {
    String ret;
    try {
        @SuppressLint("PrivateApi")
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");

        @SuppressWarnings("rawtypes")
        Class[] paramTypes = {String.class};
        Method get = SystemProperties.getMethod("get", paramTypes);

        Object[] params = {key};
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // hoge.fugaというキー読み込む
    String result = readSystemProperties("hoge.fuga");
}

最後に

SystemProperties経由で、アプリA→アプリBへのデータ渡しが簡単に行える半面、端末を再起動すると設定したSystemPropertiesの値が吹っ飛んでしまうため、使い方を選ぶ必要があると思う



もう時期、春イカのシーズンがくるので釣りに行きたい40代おっさんのたわごとでした

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0