Skip to content

Instantly share code, notes, and snippets.

@ryokosuge
Last active August 29, 2015 14:05
Show Gist options
  • Save ryokosuge/ba2249cc1b07b0cfc3f1 to your computer and use it in GitHub Desktop.
Save ryokosuge/ba2249cc1b07b0cfc3f1 to your computer and use it in GitHub Desktop.
【Android】Androidのアプリ間で情報を共有する方法 rel : http://blog.ryochin.xyz/archives/41
public class MyShared {
private Context context;
private SharedPreferences sp;
private String packageName;
private static final String ADD_NAME = "test";
private static final String KEY = "KEY";
private static final String DEFAULT_VALUE = "";
public MyShared(Context context) {
this.context = context;
// アプリのパッケージ名を取得
this.packageName = this.context.getPackageName();
// パッケージ名+付加名でSharedPreferencesを生成
// MODEは他のアプリも参照できる様にContext.MODE_WORLD_READABLEにする
this.sp = this.context.getSharedPreferences(
this.packageName + ADD_NAME, Context.MODE_WORLD_READABLE);
}
/**
* this.spに保存されている値を取得する
*
* @return KEYに保存されている値
*/
public final String getValue() {
// ローカルファイルの値を取得
String value = this.getLocalPreferencesValue();
if (value.equals(DEFAULT_VALUE)) {
// 取得した値がDEFALUT_VALUEと同じならば
// this.spに値を保存する
this.setValue();
// 再度値を取得する
value = this.getLocalPreferencesValue();
}
return value;
}
/**
* this.spに値を保存する
*/
public final void setValue(String newValue){
// 他のアプリから値を取得
String value = this.getExternalPreferencesValue();
if (value.equals(DEFAULT_VALUE)) {
// 他にインストールされているアプリに値がない場合ここで値を生成
value = newValue;
}
// 値をアプリのSharedPreferencesに保存
Editor editor = this.sp.edit();
editor.putString(KEY, value);
editor.commit();
}
/**
* this.spにKEYで保存されている値を取得する
*
* @return 値があったら値 or なかったらDEFAULT_VALUE
*/
private final String getLocalPreferencesValue() {
return this.sp.getString(KEY, DEFAULT_VALUE);
}
/**
* 他にインストールされているアプリを取得して 自分で作ったSharedPreferencesを取得して値があるか確認
*
* @return 値があったら値 or なかったらDEFAULT_VALUE
*/
private final String getExternalPreferencesValue() {
// インストールされているアプリ情報の取得
List<ApplicationInfo> appInfo = this.context.getPackageManager().getInstalledApplications(0);
// Iteratorに変換
Iterator<ApplicationInfo> iterator = appInfo.iterator();
String value = null;
// アプリ情報がある限りループ
while (iterator.hasNext()) {
// 一つのアプリ情報を取得
ApplicationInfo info = iterator.next();
try {
// 取得したアプリ情報のContextクラスを生成
Context c = this.context.createPackageContext(info.packageName, 0);
// 取得したアプリ情報のパッケージ名+付加名でSharedPreferenceを生成
// MODEは他のアプリからも参照できるようにContext.MODE_WORLD_READABLEで
// ※MODEに関しては値を保存するわけではないのでContext.MODE_PRIVATEでも問題ないかも
SharedPreferences sp = c.getSharedPreferences(info.packageName + ADD_NAME, Context.MODE_WORLD_READABLE);
// 値の取得
value = sp.getString(KEY, DEFAULT_VALUE);
// 値がDEFAULT_VALUEと違うならばループを抜ける
if (!value.equals(DEFAULT_VALUE)) {
break;
}
} catch (NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment