Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 인텐트(Intent)의 종류와 활용 방법 완벽 가이드

인텐트(Intent)란 무엇인가?

인텐트의 종류를 살펴보기 전에, 먼저 인텐트가 무엇인지 이해할 필요가 있습니다. 인텐트(Intent)는 안드로이드에서 특정 작업(action)을 수행하기 위해 컴포넌트 간에 전달되는 메시징 객체입니다. 주로 새로운 액티비티를 시작하거나, 브로드캐스트 리시버를 전송하고, 서비스를 시작하며, 두 액티비티 사이에 데이터를 전달하는 용도로 활용됩니다.

안드로이드에서 제공하는 인텐트는 크게 두 가지 유형으로 나뉩니다.

  • 명시적 인텐트(Explicit Intent)
  • 암시적 인텐트(Implicit Intent)

1. 명시적 인텐트(Explicit Intent)

명시적 인텐트는 애플리케이션 내부 세계를 연결하는 데 사용됩니다. 예를 들어 새로운 액티비티를 시작하거나, 두 액티비티 간에 데이터를 주고받을 때 활용합니다.

새로운 액티비티를 시작하려면 Intent 객체를 생성한 후, 소스(source) 액티비티와 목적지(destination) 액티비티를 아래와 같이 전달해야 합니다.

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

또한 SecondActivity를 AndroidManifest.xml 파일에 반드시 선언해야 합니다. 선언하지 않으면 실행 시점에 런타임 예외(Runtime Exception)가 발생합니다. 선언 예시는 다음과 같습니다.

<activity android:name = ".SecondActivity"></activity>

2. 암시적 인텐트(Implicit Intent)

암시적 인텐트는 외부 애플리케이션과 연결할 때 사용됩니다. 대표적인 예로 전화 걸기, 이메일 보내기, 웹사이트 열기 등이 있습니다. 암시적 인텐트에서는 아래 예시처럼 setAction() 메서드를 통해 수행할 동작(action)을 지정해야 합니다.

Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("www.tutorialspoint.com"));
startActivity(i);

위 예제에서는 동작을 'view'로 지정했습니다. 따라서 setData() 메서드에 설정된 내용을 화면에 표시하게 됩니다.

URI 및 MIME 타입 관련 주요 메서드

setData()          - URI만 지정합니다.
setType()          - MIME 타입만 지정합니다.
setDataAndType()   - URI와 MIME 타입을 모두 지정합니다.

실습 예제: 명시적·암시적 인텐트 통합 구현

이번 예제에서는 실제 프로젝트를 만들어 인텐트를 직접 사용하는 방법을 단계별로 알아보겠습니다.

Step 1 — 새 프로젝트 생성

Android Studio를 열고 File ⇒ New Project 메뉴로 이동한 뒤, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다.

Step 2 — 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent"
    android:layout_height = "match_parent">
<LinearLayout
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:gravity = "center"
    android:orientation = "vertical">
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Start website"
        android:id = "@+id/send"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

Step 3 — MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button send = findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setAction(Intent.ACTION_VIEW);
                i.setData(Uri.parse("https://www.tutorialspoint.com"));
                startActivity(i);
            }
        });
    }
}

Step 4 — 인터넷 권한 추가

웹사이트를 열기 위해서는 인터넷 권한이 필요합니다. AndroidManifest.xml 파일에 아래와 같이 인터넷 권한을 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
    <application
        android:allowBackup = "true"
        android:icon = "@mipmap/ic_launcher"
        android:label = "@string/app_name"
        android:roundIcon = "@mipmap/ic_launcher_round"
        android:supportsRtl = "true"
        android:theme = "@style/AppTheme">
        <activity android:name = ".MainActivity">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />
                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 모바일 기기에 기본 화면이 표시됩니다.

화면에서 'Start website' 버튼을 클릭하면, 암시적 인텐트에 의해 tutorialspoint 웹사이트로 자동으로 이동하는 것을 확인할 수 있습니다.

마무리 정리

지금까지 안드로이드의 두 가지 인텐트 유형을 살펴보았습니다. 명시적 인텐트는 앱 내부의 특정 컴포넌트를 정확히 지정하여 호출할 때 사용하고, 암시적 인텐트는 수행할 동작만 지정하여 해당 작업을 처리할 수 있는 외부 앱에 요청할 때 사용합니다. 두 인텐트의 차이를 명확히 이해하면 액티비티 전환, 외부 앱 연동 등 안드로이드 개발의 핵심 기능을 더욱 효과적으로 구현할 수 있습니다.