|
안드로이드(Android) 개발 컴포넌트 공유 객체 Application 만들어서 사용하는 방법 |
|
환경: Android Studio |
안드로이드 Application Class 는 어느 컴포넌트(component) 에서나 공유할 수 있는 전역 클래스입니다. 컴포넌트들 사이에서 공동으로 관리할 데이터가 있다면 Application Class를 상속받아 만든 클래스를 사용합니다. 등록은 AndroidManifest.xml 에 하며, getApplicationContext() 함수로 객체에 접근할 수 있습니다. 안드로이드에서 컴포넌트는 액티비티(Activity), 서비스(Service), 방송수신자(Broadcast receiver), 콘텐츠 제공자(Content provider), 인텐트(Intent) 입니다.
아래에 나열한 순서대로 샘플을 구현해 보겠습니다.
l android.app.Application Class 를 상속받아 클래스를 만듭니다.
l AndroidManifest.xml 에 있는 <application> 의 name 속성에 클래스를 등록합니다.
l getApplicationContext() 함수로 Application 객체의 참조값을 얻습니다.
먼저 Application class 를 상속받아 사용자정의 클래스를 작성합니다. 기본적으로 Override 해야 하는 함수는 3가지 입니다. 그리고 id 와 pwd 변수에 보관된 정보를 공유하기 위해 추가했습니다.
l onCreate : 앱 생성될 때 호출됩니다. 모든 상태변수와 리소스 초기화 로직을 이곳에서 관리합니다.
l onLowMemory : 시스템의 리소스가 부족할 때 발생합니다.
l onConfigurationChanged : 컴포넌트가 실행되는 동안 기기의 설정 정보가 변경될 때 시스템에서 호출합니다.
import android.app.Application;
import android.content.res.Configuration;
public class CustomApplication extends Application {
private String id = "gon";
private String pwd = "1111";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
두 번째는 만든 Application class 를 application 태그의 name 속성에 등록합니다.
세 번째는 getApplicationContext() 함수를 이용해서 Application 객체를 참조합니다. 그리고 Application 에 저장한 id 와 pwd 정보를 가져 옵니다.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomApplication app = (CustomApplication) getApplicationContext();
TextView txtViewId = (TextView)findViewById(R.id.textView1);
TextView txtViewPwd = (TextView)findViewById(R.id.textView4);
// 정보 셋팅
txtViewId.setText(app.getId());
txtViewPwd.setText(app.getPwd());
}
}'안드로이드 개발' 카테고리의 다른 글
| 안드로이드 개발 생성자 추가하는 방법, There is no default constructor available in (0) | 2017.12.23 |
|---|---|
| 안드로이드 개발 RelativeLayout 화면을 Java 소스에서 구현하는 방법 (0) | 2017.12.17 |
| 안드로이드 개발 No orientation specified, and the default is horizontal. This is a common source of bugs when children are added dynamically. 에러 해결 (0) | 2017.12.06 |
| 안드로이드 개발 Android WebView 로컬 HTML 파일 표현하는 방법 (0) | 2017.12.04 |
| 안드로이드 개발 가로/세로 화면 전환할 때 배경화면 변경하는 방법 (0) | 2017.11.27 |
| 안드로이드 개발 ViewHolder 패턴 이용해서 ListView 성능 향상하는 방법 (0) | 2017.11.22 |
| 안드로이드 폰캡 PhoneGap 설치방법, 기본 앱 만들어서 실행하는 방법 (1) | 2017.11.12 |
| 이클립스(Eclipse) 안드로이드 에뮬레이터 연결해서 실행하는 방법 (3) | 2016.11.17 |
