'Android Intent sample'에 해당되는 글 1건

앞번에 Intent 와 Intent Filter 에 관한 개념에 대한 설명을 했습니다. 


이번에는 앞서 언급한 명시적 인텐트 와 암시적 인텐트의 사용 예를 보여 드리겠습니다. 


■ 명시적 인텐트 예제


명시적 인텐트는 시작할 구성 요소(호출될 Activity)의 이름을 지정 하는 것입니다. 

아래는 ActivityA 에서 ActivityB를 명시적으로 호출 하는 예제 입니다. 


activity_a.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.tutorial.james.androidtutorialtest.MainActivity"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity A 입니다."/>

<Button
android:id="@+id/btn_goto_activityb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity B 로 이동"/>

</LinearLayout>

</LinearLayout>

Activity A 화면이라는 내용의 TextView 를 제공하고 바로 아래에 Button 컴포넌트를 두어 Activity B 로 이동 하는 이벤트를 걸도록 하겠습니다. 


ActivityA.java

package com.tutorial.james.androidtutorialtest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class ActivityA extends AppCompatActivity {

Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);

intent = new Intent(this, ActivityB.class);
(findViewById(R.id.btn_goto_activityb)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent.putExtra("messageStr", "Activity B 에 전송하는 문자 메세지입니다.");
intent.putExtra("messageInt", 7);
startActivity(intent);
}
});
}

}

btn_goto_activityb 라는 id 값을 가진 컴포넌트가 클릭 될 경우 intent 에 putExtra 를 이용하여 ActivityB 로 전달하고 싶은 내용을 추가 했습니다. 

messageStr 이라는 key 값에는 string 형태로 전달하고, messageInt 라는 Key 값에는 inter 형태로 전달 했습니다. 

이 값들을 Activity B 에서 사용 하는 방법도 아래에서 보여 드리겠습니다. 


activity_b.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.tutorial.james.androidtutorialtest.MainActivity"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity B 입니다."/>

<TextView
android:id="@+id/tv_getintent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

</LinearLayout>

Activity B 화면임을 알려 주고 바로 아래 tv_getintent 라는 id 값의 TextView 를 제공하여 여기에 앞에서 전달흔 값들을 셋팅해 보겠습니다. 


ActivityB.java

package com.tutorial.james.androidtutorialtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class ActivityB extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);

if(getIntent().getExtras() != null){
String str = "Activity A 에서 전달한 Int 값 = "+getIntent().getExtras().getInt("messageInt")
+"\nActivity A 에서 전달한 string 값 = "+ getIntent().getExtras().getString("messageStr");
((TextView)(findViewById(R.id.tv_getintent))).setText(str);
}

}
}

getIntent().getExtra() 값이 null 이 아닌 경우 이전 Activity 에서 intent 에 데이터를 전달 했다는 것을 알 수 있습니다. 

putExtra 할 때 int 값을 던졌으면 getIntent().getExtra().getInt("키값") 으로 받아야 하고, 만약 string 값을 던졌으면 getIntent().getExtra().getString("키값") 으로 받으면 됩니다. 


참고로 이 getIntent().getExtra() 는 데이터를 포함하는 Intent 의 Bundle 객체를 반환합니다. 


이를 실행 해보면 아래와 같은 결과를 얻으실 수 있습니다. 


Activity A 화면으로 Activity B 로 이동하는 버튼을 제공하고 있습니다. 


위 ActivityB.java 파일에서 getIntent().getExtra() 한 값들을 문자열로 조합하여 찍어 낸 결과 입니다. 


명시적 인텐트는 아주 간단하지만 또 한편으로는 데이터 전달 방식이 생각보다 종류가 많아 잘 봐두셔야 합니다. 

실제로 앱 개발중 Intent 를 활용하여 데이터를 쉬지 않고 나르고 받아 오는 작업을 할 겁니다. 



■ 암시적 인텐트 예제

암시적 인텐트는 호출될 Activity 명을 참조하는 명시적 인텐트와 달리 수행될 액션과 수신 Activity 에 의해 처리되는 데이터 타입을 지정하여 호출 될 Activity 를 식별합니다. 


아래는 email 를 보내는 기능을 하는 Activity를 검색하여 실행 하는 예제입니다. 


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.tutorial.james.androidtutorialtest.MainActivity"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>

<Button
android:id="@+id/btn_send_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_send_email"
/>

</LinearLayout>

</LinearLayout>

레이아웃에 버튼 하나만 배치 했습니다. 

id 값을 btn_send_email 로 설정 하였습니다. 

text 값은 string.xml 파일의 btn_sent_email 이라는 값을 참조 하도록 했으며 이 값은 아래와 같습니다. 

<string name="btn_send_email">Send email</string>



IntentActivity.java

package com.tutorial.james.androidtutorialtest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

/**
* Created by James on 2017-08-09.
*/

public class IntentActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

(findViewById(R.id.btn_send_email)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "beardog78@gmail.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "제목");
intent.putExtra(Intent.EXTRA_TEXT, "메일 내용 입력");
startActivity(Intent.createChooser(intent, "Send Email"));
}
});


}
}

IntentActivity 의 레이아웃은 activity_main.xml 이라고 설정 했습니다. 

이메일을 전송하기 위해서는  Intent.ACTION_SEND 값을 전달해야 합니다. 

btn_send_email 이라는 id 값을 가지는 컴포넌트를 찾아 View.OnClickListener 를 붙여 클릭 이벤트가 발생 할 경우 이메일을 전송합니다. 


위 소스를 실행 시 아래와 같은 결과를 확인 할 수 있습니다. 


SEND EMAIL 이라는 텍스트 있는 버튼을 클릭 시 아래와 같이 현재 단말에서 ACTION_SEND 를 할 수 있는 모든 애플리케이션 목록이 아래와 같이 나타납니다. 사용자는 이중 본인이 원하는 애플리케이션을 사용하여 이메일 전송을 할 수 있습니다. 




지금까지 명시적 인텐트 및 암시적 인텐트의 사용 예제를 살펴 봤습니다. 


Gooooooooooooooooooood Bye :)


블로그 이미지

쉬운코딩이최고

Android, Java, jsp, Linux 등의 프로그래밍 언어를 소개 합니다.

,