onCreate() 또는 onDestroy() 등 앱이 완전히 종료되고 새롭게 시작되는 것이 아닌,

잠시 어플이 화면에서 사라졌다가 다시 나타나는 경우(ex 전화가 와서 현재 어플이 화면에서 보이지 않게 되고, 잠시 뒷전이 됨) 현재 어플이 종료되고, 입력된 정보가 사라질 수도 있다.

이와 같은 상황에서 데이터를 유지시키기 위해서는 데이터를 저장하고, 복구하는 코드를 작성해야 할 것이다.

 

이때, SharedPreferences를 활용하면 문제를 해결할 수 있다.

(외에도 onSaveInstanceState(), onRestoreInstanceState() 를 사용하는 방법도 있다)

 

* onPause() 메소드

@Override
protected void onPause(){
	super.onPause();
    
    SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    // can be any other name than "pref", 단 onResume()에 사용되는 이름과 동일한 이름을 사용해야한다.
    SharedPreferences.Editor editor = pref.edit();
    
    // 필요한 정보를 editor객체에 저장시킨다.
    editor.putString("name", "소녀시대");
    
    // commit
    editor.commit();
}

* onResume() 메소드

@Override
protected void onResume(){
	super.onResume();
    
    SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    if(pref != null) // 저장된 데이터가 있는경우
    {
    	String name = pref.getString("name", ""); // 두번째 parameter: 저장된 name값이 없는경우 사용할 default 값. 현재는 빈 문자열로 세팅됨
        
        // 불러온 데이터 활용
        // Toast.makeText(this, "복구된 이름: "+name, Toast.LENGTH_LONG).show();
    }
}

+ Recent posts