마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

remote service 사용하면서 SharedPreferences를 singleton으로 사용하는 법

0 추천

* process가 :remote로 돌아가는 서비스가 있습니다. 이건 바꿀 수가 없어요.

* 그리고 singleton으로 사용 중인  SharedPreferences가 있습니다.
SharedPreferences는 context를 넘겨주기 귀찮아서 상속을 한 번 더 합니다.

 

public class BasePreferenceHelper
{
  private SharedPreferences _sharedPreferences;
    
  protected BasePreferenceHelper(Context $context)
  {
    super();
    _sharedPreferences = $context.getSharedPreferences($context.getPackageName(), Context.MODE_MULTI_PROCESS);
  }
  // ... get, put 등의 일을 함 
}

 

public class PreferenceHelper extends BasePreferenceHelper
{
  private static PreferenceHelper _instance = null;
  private Context _context;

  public static synchronized PreferenceHelper instance(Context $context)
  {
    if (_instance == null)
      _instance = new PreferenceHelper($context);
    return _instance;
  }

  protected PreferenceHelper(Context $context)
  {
    super($context);
    _context = $context;
  }
  // key를 이용한 실제 값 저장.
}

 

:remote 때문에 Context.MODE_MULTI_PROCESS를 사용해야하는 건 괜찮은데, 문제는 if (_instance == null) 이 부분이 없어야 변경된 값을 가져옵니다. 즉 singleton의 의미가 없어져버려요....

 

매번 context를 넘기지 않고, singleton은 아니어도 되지만 실제 사용할 때 매번 new PreferenceHelper()로  사용하지 않아도 되는 좋은 방법 없나요?

쎄미 (162,410 포인트) 님이 2014년 4월 11일 질문

2개의 답변

+1 추천
 
채택된 답변
1. 서로 다른 프로세스간에 singleton 객체를 공유하는 방법은 없습니다.

2. context 객체를 static 객체의 필드로 저장하지 마세요. 온갖 흉악한 문제가 생깁니다.
익명사용자 님이 2014년 4월 14일 답변
쎄미님이 2014년 4월 15일 채택됨
+1 추천
1. 일단.. 가로는 넣어주심이 저 버릇 때문에 피본 분들 많이 봐왔습니다. 
 
if (_instance == null) {
      _instance = new PreferenceHelper($context);
}
 
or 
 
if (_instance == null) _instance = new PreferenceHelper($context);
 

2. 전 아래와 같이 항상 context 를 갱신 하도록 사용 합니다. context 가 어차피 유지가 안되니 계속 갱신해서 사용하는 수 밖에 없더라구요

if (_instance == null) {
      _instance = new PreferenceHelper();
}
_instance.setContext($context);
 
return _instance;
 
aucd29 (218,390 포인트) 님이 2014년 4월 14일 답변
저는 setContext를 또 해줘도 안되네요 ㅠㅠ
...