프로그래밍/안드로이드

안드로이드 - Application 객체를 이용한 전역 변수 만들기

가카리 2015. 8. 26. 21:44
반응형

 

프로세스의 아래에는 단 하나의 유일한 Application 객체가 있고 그아래 컴포넌트인 서비스, 브로드캐스트 리시버, 액티비티, 콘텐트 프로바이더로 구성된다.

 

Application 클래스가 모든 컴포넌트보다 우선적으로 생성되고 유일한 객체만 생성되므로 전역 변수를 두기에는 제일 좋은 곳이다.

 

그리고 Application 객체의 멤버는 프로세스의 어디에서나 참조할 수 있다.

 

    void onCreate()

    void onTerminate()

    void onConfigurationChanged(Configuration newConfig)

    void onLowMemory()

 

onCreate는 응용프로그램이 실행된 직후 호출된다. 다른 컴포넌트인 서비스, 브로드캐스트 리시버, 액티비티, 콘텐트 프로바이더보다 먼저 실행되므로

 

이 메소드가 진입점이 된다.

 

onTerminate는 모든 컴포턴트가 없어진 후 호출된다.

 

onConfigurationChanged와 onLowMemory는 환경 변화나 메모리가 부족할 때 호출된다.

 

액티비티나 서비스에서는 다음 메소드로 Application 객체를 구한다.

 

    final Application getApplication()

 

다음 예제는 Application 객체에 전역변수를 만들고 액티비티에서 전역변수를 가져오는 예제이다.

 

 

activity_application_test.xml

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

    android:orientation="vertical"

>

 

<TextView

android:id="@+id/mode"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="현재 모드 : "

android:textSize="20sp"

/>

<Button

android:id="@+id/beginner"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="초보자 모드"

/>

<Button

android:id="@+id/professional"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="숙련자 모드"

/>

 

</LinearLayout>

 

ApplicationTest.java

 

package com.example.ch13_applicationtest;

 

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

 

 

public class ApplicationTest extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_application_test);

      

        UpdateNowMode();

    }

 

    void UpdateNowMode(){

        TextView txtMode = (TextView)findViewById(R.id.mode);

        AndTest_Application app = (AndTest_Application)getApplication();

        if(app.getMode() == AndTest_Application.BEGINNER){

            txtMode.setText("현재 모드 : 초보자 모드");

        }else{

            txtMode.setText("현재 모드 : 숙련자 모드");

        }

    }

    

    public void mOnClick(View v){

        AndTest_Application app = (AndTest_Application)getApplication();

        switch(v.getId()){

        case R.id.beginner:

            app.setMode(AndTest_Application.BEGINNER);

            break;

        case R.id.professional:

            app.setMode(AndTest_Application.PREFESSIONAL);

            break;

        }

        UpdateNowMode();

    }

    

}

 

AndTest_Application.java

 

package com.example.ch13_applicationtest;

 

import android.app.Application;

 

public class AndTest_Application extends Application{

    

    private int mMode;

    //전역변수를 전언함

    static final int BEGINNER = 0;

    static final int PREFESSIONAL = 1;

    

    public void onCreate(){

        super.onCreate();

        mMode = BEGINNER;//mMode 초기화

    

    }

    

    public void onTerminate(){

        super.onTerminate();

    }

    

    //mMode 값을 불러오는 메소드

    public int getMode(){

        return mMode;

    }

    

    //mMode 세팅하는 함수

    public void setMode(int aMode){

        mMode = aMode;

    }

}

 

프로그램 시작 직후에 객체를 생성해야 하므로 매니페스트에는 이 객체의 이름을 반드시 명시해야 한다.

application 태그에 name 속성으로 클래스명을 밝혀 놓으면 태스크가 생성될 때 객체가 생성되고 전역 멤버가 초기화된 후 각 액티비티의

라이플 사이클 메소드가 호출 된다.

 

AndroidManifest.xml 파일

 

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme"

android:name="com.example.ch13_applicationtest.AndTest_Application"

>

 

실행 화면

 

 

반응형