• 검색 결과가 없습니다.

학습목표

N/A
N/A
Protected

Academic year: 2022

Share "학습목표"

Copied!
17
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

12차시 액티비티와 인텐트

1 학습목표

❍ 안드로이드 컴포넌트를 이해할 수 있다.

❍ 인텐트의 개념과 활용법을 알 수 있다.

❍ 액티비티와 인텐트의 기본 사용법을 알 수 있다.

2 확인해 볼까?

지금까지의 안드로이드 앱 화면 구성은 실행할 때 출력되는 화면 하나밖에 없 다. 우리가 사용하는 대부분의 앱은 다수의 화면으로 구성되어 사용자의 입력 이 벤트에 따라 화면이 전환되는데 어떻게 하면 이것을 구현할 수 있을까?

3 액티비티와 인텐트의 개요

1) 학습하기

❍ 안드로이드 애플리케이션

안드로이드와 같은 모바일 플랫폼은 일반적인 컴퓨터의 실행 환경과는 차이가 있다. 일반적인 컴퓨터에서는 애플리케이션 단위로 실행이 되지만 안드로이드에 서는 액티비티 단위로 실행이 된다.

안드로이드 애플리케이션에서의 액티비티는 하나의 화면을 의미하며, 애플리케 이션은 일반적으로 한 개 이상의 액티비티들로 구성이 된다. 안드로이드 안에는 이메일, 문자 메시지, 주소록, 카메라. 메모, 일정, 달력 등과 같은 많은 애플리케 이션들이 이미 내장되어 있다.

❍ 액티비티

액티비티는 안드로이드폰에 나타나는 화면 하나하나를 말하며 사용자 인터페이

스 화면을 제어하는 역할을 한다. 즉, UI를 화면에 표시하고 시스템이나 사용자의

(2)

반응을 처리하는 클래스이다. 애플리케이션을 작성한다는 것은 결국 액티비티를 하나씩 작성한 후에 하나로 조립하는 것이라고 할 수 있다.

따라서 애플리케이션을 실행시키면 실제는 애플리케이션의 첫 번째 액티비티가 실행되는 것이고, 첫 번째 액티비티의 UI에서 사용자의 선택에 따라 다른 액티비 티가 실행되는 것이다. 하나의 액티비티에서 다른 액티비티를 시작하려면 startActivity() 메서드를 사용하여 호출한다.

❍ 액티비티의 생명주기

액티비티는 기본적으로 다음과 같은 3가지의 상태를 가진다.

• 실행 상태(resumed, running)

사용자가 현재 조작중인 액티비티를 말하며 액티비티가 전경(foreground)에 위치하 고 있다.

• 일시멈춤 상태(paused)

현재 액티비티의 일부가 화면에는 보여지지만 전경 상태는 아니다. 다른 액티비티 가 전경에 있는 상태이다.

• 정지 상태(stopped)

액티비티가 화면에서 전혀 보이지 않는 상태이다. 액티비티는 배경(background)에 위치한다. 아직까지는 상태와 멤버 정보를 가지고 있다. 하지만 시스템이 메모리가 필요하면 언제든지 종료시킬 수 있다.

액티비티는 위의 상태 중의 하나를 번갈아 가지게 된다. 안드로이드 시스템은 애플리케이션 프로세스를 관리하다가 메모리가 부족해지면 중요도가 낮은 프로세 스를 제거하게 되는데 액티비티의 상태에 따라 중요도를 분류할 수 있다.

❍ 인텐트

인텐트는 안드로이드 구성하는 컴포넌트인 액티비티, 서비스, 브로드캐스트 리

시버를 호출하거나 호출할 때 데이터를 전달해주는 역할을 한다. 애플리케이션

(3)

안의 액티비티들은 단독으로 실행되기도 하지만 다른 액티비티에 의해 실행되기 도 한다. 또한 다른 애플리케이션의 액티비티들을 실행하기도 한다.

다른 액티비티를 시작할 때 액티비티의 실행에 필요한 데이터를 전달해야 하는 데 이 때 사용하는 메시지를 인텐트(Intent)라고 한다.

• 명시적 인텐트(explicit intent)

명시적 인텐트는 호출하거나 데이터를 전달할 컴포넌트가 정확히 명시되어 있는 인텐트를 말한다. 대상 컴포넌트가 명확할 경우 아래 그림과 같이 컴포넌트의 이름 을 인텐트에 넣어주면 인텐트에 의하여 해당 컴포넌트가 호출되거나 해당 컴포넌 트에 데이터가 전달되게 된다.

명시적 인텐트는 다른 액티비티의 이름을 명확히 지정할 때 사용하는 방법이 다. 또한 명시적으로 새로 실행시킬 액티비티를 지정하기 위해서 새로운 액티비 티를 생성한 후 이를 매니페스트 파일 안에 포함시켜야 한다.

Intent intent = new Intent(MainActivity.this, SubActivity.class);

startActivity(intent);

Intent()생성자의 두 번째 파라미터에서 호출할 액티비티 클래스를 지정한다. 여 기서는 SubActivity를 호출하기 위해서 SubActivity.class를 지정했다. 그리고 startActivity(intent)로 생성한 인텐트를 넘겨서 서브액티비티를 실행한다.

위의 그림을 보면, putExtra()를 이용해 데이터를 인텐트에 필요한 만큼 넣은

후에 startActivity()로 다른 액티비티로 인텐트를 넘김을 알 수 있다. 인텐트를 받

(4)

은 액티비티에서는 getStringExtra(), getIntExtra(), getBooleanExtra() 등의 메서드 로 넘어온 데이터에 접근할 수 있다.

2) 활동하기 ❍ 활동 개요

다음 실행 화면과 같이 명시적 인텐트를 이용하여 현재의 액티비티에서 다른 액티비티를 시작하는 애플리케이션을 작성해보자.

버튼을 누르면 SecondActivity 로 이동

버튼을 누르면 finish() 메서드 를 호출, 현재 액티비티를 종료 한다.

❍ 활동 과정

① 프로젝트 정보

• Application Name : IntentTest

• Project Name : IntentTest

• Package Name : com.example.intenttest

• Minimum Required SDK : API 8

• Target SDK : API 16: Android 4.1.2 (Jelly Bean)

• Compile With : API 16: Android 4.1.2 (Jelly Bean)

• Activity Name : MainActivity, SecondActivity

• Layout Name : main, second

(5)

② MainActivity의 화면을 구성하는 코드는 main.xml이지만 실제 MainActivity.java 가 액티비티에 해당된다. 물론 main.xml을 사용하지 않고 java 코드만으로도 화면을 구성하기도 하지만 일반적으로 액티비티 하나당 화면을 하 나씩 생성할 수 있으므로 XML 파일 하나를 만들어서 사용한다.

다음 그림은 프로젝트의 Layout에 XML을 추가하는 것과 패키지에 Java 소스

를 추가하는 것을 나타낸 것이다.

(6)

AndroidManifest.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

<?xml version="1.0" encoding="utf-8"?>

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

package="com.example.intenttest"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="com.example.intenttest.MainActivity"

android:label="@string/app_name" >

③ AndroidManifest.xml

(7)

main.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15

<?xml version="1.0" encoding="utf-8"?>

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

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="여기는 Main Activity"/>

<Button

android:id="@+id/btn1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Second Activity로 이동"/>

</LinearLayout>

10~14행: 두 번째 액티비티를 호출하기 위한 버튼을 정의한다.

second.xml

1 <?xml version="1.0" encoding="utf-8"?>

17 18 19 20 21 22 23 24 25 26

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity

android:name="SecondActivity"

android:label="SecondActivity"></activity>

</application>

</manifest>

22~24행: 프로젝트 생성시 자동으로 추가된 첫 번째 액티비티 외에 추가로 생성 한 액티비티는 매니페스트 파일에 추가해 줘야 한다.

④ XML 코드: main.xml

⑤ XML 코드: second.xml

(8)

MainActivity.java 1

2 3 4 5 6 7 8 9 10 11 12 13 14

package com.example.intenttest;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity { @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main);

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="여기는 Second Activity" />

<Button

android:id="@+id/btn1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Main Activity로 이동" />

</LinearLayout>

12~16행: 첫 번째 액티비티를 호출하기 위한 버튼을 정의한다.

⑥ Java 코딩: MainActivity.java

(9)

15 16 17 18 19 20 21 22 23

Button btn = (Button)findViewById(R.id.btn1);

btn.setOnClickListener(new OnClickListener() { public void onClick(View v) {

Intent intent = new Intent(MainActivity.this,SecondActivity.class);

startActivity(intent);

} });

} }

15행: main.xml의 버튼을 대입한다.

16~21행: 버튼 클릭 이벤트 처리를 한다. 버튼을 클릭하면 인텐트를 생성하는데 SeconActivity를 명시적으로 호출한다.

19행: startActivity()를 호출하여 SecondActivity를 시작하게 한다.

SecondActivity.java 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

package com.example.intenttest;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class SecondActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.second);

Button btn = (Button)findViewById(R.id.btn1);

btn.setOnClickListener(new OnClickListener() { public void onClick(View v) {

finish();

} });

⑦ Java 코딩: SecondActivity.java

(10)

20 21

} }

14행: second.xml의 버튼을 대입한다.

17행: 현재 액티비티를 종료한다.

3) 활동하기 ❍ 활동 개요

위의 활동하기 예제에서는 실행되고 있는 액티비티가 종료되면서 호출했던 메 인액티비티로 돌아가게 되어있다. 만약 서브 액티비티로부터 결과를 받아야 하는 경우에는 startActivity() 대신에 startActivityResult()를 호출하여서 서브액티비티 를 시작하여야 한다. 다음 실행 화면과 같이 두 번째 액티비티에서 전달받은 값 을 첫 번째 출력할 수 있도록 작성해보자.

❍ 활동 과정 ① 프로젝트 정보

• Application Name : ActivityResultTest

• Project Name : ActivityResultTest

• Package Name : com.example.activityresulttest

(11)

main.xml 1

2 3 4 5 6 7 8 9 10 11

<Button

android:id="@+id/button"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="서브 액티비티에서 데이터 받기" />

<?xml version="1.0" encoding="utf-8"?>

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

• Minimum Required SDK : API 8

• Target SDK : API 16: Android 4.1.2 (Jelly Bean)

• Compile With : API 16: Android 4.1.2 (Jelly Bean)

• Activity Name : MainActivity, SecondActivity

• Layout Name : main, second

② AndroidManifest.xml 수정: 애플리케이션에 새로 추가된 SecondActivity를 다음과 같이 선언한다.

<application

‥‥

<activity

‥‥

</activity>

<activity

android:name="SecondActivity"

android:label="SecondActivity">

</activity>

</application>

③ XML 작성: main.xml

(12)

12 13 14 15 16 17 18 19 20 21 22 23 24

<TextView

android:id="@+id/text2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="*****************************" />

<TextView

android:id="@+id/text1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="서브 액티비티에서 전달된 데이터" />

</LinearLayout>

second.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

<?xml version="1.0" encoding="utf-8"?>

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<EditText

android:id="@+id/edit"

android:layout_width="match_parent"

android:layout_height="wrap_content" >

<requestFocus>

</requestFocus>

</EditText>

<LinearLayout

android:id="@+id/linearLayout1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_gravity="center" >

④ XML 작성: second.xml

(13)

21 22 23 24 25 26 27 28 29

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="메인액티비티로 입력 데이터 전달" />

</LinearLayout>

</LinearLayout>

MainActivity.java 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

package com.example.activityresuttest;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends Activity { static final int GET_STRING = 1;

TextView text;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) { super.onCreate(icicle);

setContentView(R.layout.main);

// Find the button defined in the main.xml

Button button = (Button) findViewById(R.id.button);

text = (TextView) findViewById(R.id.text2);

⑤ Java 코딩: MainActivity.java

(14)

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

Intent i = new Intent(MainActivity.this, SecondActivity.class);

startActivityForResult(i, GET_STRING);

// Add an OnClickListener to it, that will open the SubActivity button.setOnClickListener(new OnClickListener() {

// @Override

public void onClick(View arg0) {

} });

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GET_STRING) {

if (resultCode == RESULT_OK) {

text.setText(data.getStringExtra("INPUT_TEXT"));

} } } }

28~29행: SecondActivity를 실행한다.

35~41행: SecondActivity로부터 결과를 받는다.

19행: startActivity()를 호출하여 SecondActivity를 시작하게 한다.

SecondActivity.java 1

2 3 4 5 6 7 8 9 10

package com.example.activityresuttest;

import android.app.Activity;

import android.appwidget.AppWidgetManager;

import android.appwidget.AppWidgetProvider;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

⑥ Java 코딩: SecondActivity.java

(15)

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

Intent intent = new Intent();

intent.putExtra("INPUT_TEXT", edit.getText().toString());

setResult(RESULT_OK, intent);

import android.widget.Button;

import android.widget.EditText;

public class SecondActivity extends Activity { EditText edit;

public class MyAppWidgetProvider extends AppWidgetProvider { public void onUpdate(Context context,

AppWidgetManager appWidgetManager, int[] appWidgetIds) { }

}

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.second);

edit = (EditText) findViewById(R.id.edit);

Button button = (Button) findViewById(R.id.button);

button_ok.setOnClickListener(new OnClickListener() { public void onClick(View v) {

finish();

} });

} }

30행: SecondActivity에서 문자열을 입력하고 입력완료 버튼을 누르면.

32~34행: MainActivity로 결과(문자열)를 보낸다.

35행: SecondActivity를 종료한다.

❍ 활동지

★ 프로그램 소스와 결과 화면 프린트 스크린 제시

(16)

4 배운 내용 정리

1) 안드로이드 애플리케이션과 액티비티의 개념

안드로이드와 같은 모바일 플랫폼은 일반적인 컴퓨터의 실행 환경과는 차이가 있다. 일반적인 컴퓨터에서는 애플리케이션 단위로 실행이 되지만 안드로이드에 서는 액티비티 단위로 실행이 된다. 안드로이드 애플리케이션에서의 액티비티는 하나의 화면을 의미하며, 애플리케이션은 일반적으로 한 개 이상의 액티비티들로 구성이 된다.

액티비티는 안드로이드폰에 나타나는 화면 하나하나를 말하며 사용자 인터페이 스 화면을 제어하는 역할을 한다. 즉, UI를 화면에 표시하고 시스템이나 사용자의 반응을 처리하는 클래스이다. 애플리케이션을 작성한다는 것은 결국 액티비티를 하나씩 작성한 후에 하나로 조립하는 것이라고 할 수 있다.

따라서 애플리케이션을 실행시키면 실제는 애플리케이션의 첫 번째 액티비티가 실행되는 것이고, 첫 번째 액티비티의 UI에서 사용자의 선택에 따라 다른 액티비 티가 실행되는 것이다. 하나의 액티비티에서 다른 액티비티를 시작하려면 startActivity() 메서드를 사용하여 호출한다.

2) 인텐트의 개념

인텐트는 안드로이드 구성하는 컴포넌트인 액티비티, 서비스, 브로드캐스트 리 시버를 호출하거나 호출할 때 데이터를 전달해주는 역할을 한다. 애플리케이션 안의 액티비티들은 단독으로 실행되기도 하지만 다른 액티비티에 의해 실행되기 도 한다. 또한 다른 애플리케이션의 액티비티들을 실행하기도 한다.

다른 액티비티를 시작할 때 액티비티의 실행에 필요한 데이터를 전달해야 하는 데 이 때 사용하는 메시지를 인텐트(Intent)라고 한다.

• 명시적 인텐트(explicit intent)

명시적 인텐트는 호출하거나 데이터를 전달할 컴포넌트가 정확히 명시되어 있는 인텐트를 말한다. 대상 컴포넌트가 명확할 경우 아래 그림과 같이 컴포넌트의 이름 을 인텐트에 넣어주면 인텐트에 의하여 해당 컴포넌트가 호출되거나 해당 컴포넌 트에 데이터가 전달되게 된다.

(17)

5 학습 확인하기

1) 안드로이드 애플리케이션의 실행 단위이면서 안드로이드폰에 나타나는 화면 하나하나를 무엇이라 하는가?

( )

2) 새로운 액티비티를 만들 때 안드로이드의 어떤 클래스를 상속받아서 만드는 가?

( )

3) 하나의 액티비티에서 다른 액티비티를 시작할 때 호출하는 메서드 이름은 무 엇인가?

( )

6 지식창고

❍ 참고문헌

[1] 안드로이드 프로그래밍, 우재남 이복기 저, 한빛미디어

[2] Step by Step 안드로이드 앱 개발, 장용식 김관옥 성낙현 저, 인피니티북스 [3] 안드로이드 프로그래밍, 천인국 저, 생능출판사

[4] 안드로이드 프로그래밍 정보1,2, 김상형 저, 한빛미디어

❍ 참고사이트

[1]

http://www.oracle.com/technetwork/java/index.html

[2]

http://developer.android.com

참조

관련 문서

첫 번째 증서에는 양반이 지켜야 할 의무가, 두 번째 증서에는 부당한 양반의 권리가 나타나 있다.. 12 양반이 지켜야 할 의무를 나열하여 양반의 비생산적인 모

첫 번째 문장의 선행사는 energy 이고, 두 번째 문장의 선행사는 doing your homework in the early evening 이다.. 해석 우리는 에너지를 갖고

44 글의 첫 번째 문장인 The most important thing in the Boat Race is harmony and teamwork.을 통해 Boat Race에서 가장 중요한 것은 조 화와 팀워크임을

첫 번째 , 현행 상속세가 유산 과세형을 채택하고 있고 세대생략할증과세는 유산 취득과세에 근거를 두고 있기 때문에 두 제도는 상 호모순적인 관계이다. 또한 일본의

원래 “row echelon form”의 non-zero row의 첫 번째 non-zero component를 1 로 “reduce”한 것을 “reduced row echelon form”이라고 부르는 것 같다.. 저자는

2 고맙다고 말하면서 빗자루를‘건네준’것이므로 연속동작을 나타내는 분사구문이 되도록 현재분사 handing 이 알맞다.. 3 첫 번째 빈칸에는 목적어( him

, 첫 번째 데이터와 두 번째 데이터를 비교하여 작은 데이터를 앞에 놓는다

신흥국가의 금융위기 첫 번째 단계: 선진국과는 달리 신흥국가 의 경우 금융위기는 자본시장을 개방하는 과정에서 제대로 관리 를 못했을 경우나 또는 신흥국가의