AsyncTask 를 Activity 내 Inner Class 로 만든 경우에 메모리 누수를 방지하기 위하여 static 으로 처리하고 WeakReference 를 사용하는 예제를 찾아봤다.
https://gist.github.com/rorist/459787 에 나온 방법과 https://medium.com/google-developer-experts/finally-understanding-how-references-work-in-android-and-java-26a0d9c92f83 는 비슷한 방법이 나온다.
내가 참조하여 사용한 방법은 https://stackoverflow.com/questions/19551484/android-do-i-have-to-have-weakreference-for-inner-class-asynctask 에 나온 걸 활용했다.
잘못 사용하고 있는지 여부는 좀 더 테스트를 해보련다.
public static class saveContactsFromDbData extends AsyncTask<String, Void, String> {
private WeakReference<SaveContactsActivity> weakActivity;
SaveContactsActivity activity;
long start; // 서버에서 가져오는 시간 측정
@SuppressLint("SimpleDateFormat")
SimpleDateFormat FORMATTER = new SimpleDateFormat("mm:ss.SSS");
int newcnt = 0;
int upcnt = 0;
int no_cnt = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
weakActivity = new WeakReference<SaveContactsActivity>(activity);
}
@Override
protected String doInBackground(String... params) {
start = System.currentTimeMillis();
JSONArray peoples = null;
try {
JSONObject jsonObj = new JSONObject(params[0]);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
return null;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (weakActivity.get() != null) {
// 메모리 비우기
contactMap.clear();
}
}
}
'안드로이드 > 버그탈출' 카테고리의 다른 글
안드로이드 스튜디오 SDK22 변경시 (0) | 2017.09.15 |
---|---|
안드로이드 스튜디오 Some file crunching failed, see logs for details afer update gradle (0) | 2017.08.03 |
안드로이드 메모리 누수 관리 ★★★★★ (0) | 2017.08.01 |
삼성폰 S7 Unrecognized profile 2130706433 for video/avc (0) | 2017.07.25 |
안드로이드 uses-permission (0) | 2017.06.05 |