Context 개념

- 지금 현재 사용되고 있는 어플리케이션(액티비티)에 대한 포괄적인 정보를 지니고있는 객체

- Application Context는 안드로이드 어플리케이션의 핵심 기능을 위한 중심부

- Context는 여러 Activity 인스턴스들 간에 리소스를 공유하거나 설정등에 접근하기 위해 사용

- 현재의 프로세서에서 Application Context는 getApplicationContext() 메서드를 사용하여 얻음

- Activity는 Context 클래스를 상속 확장한 것

1
Context context = getApplicationContext(); 

cs


어플리케이션 리소스 얻기

Context의 getResources() 메서드를 이용하여 어플리케이션의 리소스를 얻을 수 있음

1
String greeting = getResources().getString(R.string.hello); 

cs

 

Application Preferences 이용하기

Context의 getSharedPreferences 메서드를 이용하면 SharedPreferences 클래스를 사용

SharedPreferences 클래스는 어플리케이션의 환결설정과 같은 간단한 데이터들을 저장.

아래는 SharedPreferences를 이용하여 사용자 이름과 성별을 저장하는 간단한 예제 입니다.

1
2
3
4
5
6
7
8
9
SharedPreferences settings = getSharedPreferences(“User”, MODE_PRIVATE);   
 
SharedPreferences.Editor prefEditor = settings.edit();   
  
prefEditor.putString(“UserName”, “Spunky”);   
  
prefEditor.putString(“SEX”, "Man");   
  
prefEditor.commit();  

cs

preference 세팅을 얻으려면 아래와 같이 해줄 수 있습니다.

1
2
3
4
SharedPreferences settings = getSharedPreferences(“User”, MODE_PRIVATE);   
  
String userName = settings.getString(“UserName”, “androidnote (Default)”);   
 

cs


Contexts를 이용하여 다른 어플리케이션의 기능을 접근하기

- Activity 실행

- System-level 서비스 프로바이더 요청 ( ex : location service )

- Application의 파일, 폴더, 데이터베이스 다루기

- Application permission 검사





출처 :
http://androidnote.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-Context%EB%9E%80-%EA%B8%B0%EB%8A%A5%EA%B3%BC-%EC%82%AC%EC%9A%A9-%EB%B0%A9%EB%B2%95


'Programming > Android' 카테고리의 다른 글

HttpURLConnection  (0) 2016.08.25
SharedPreferences  (0) 2016.08.24
Activity 생명주기  (0) 2016.08.24
Fragment  (0) 2016.08.24
permission  (0) 2016.08.24

+ Recent posts