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

안드로이드 인텐트 필터(Intent Filter)란 무엇이며, 어떻게 사용할까?

인텐트 필터의 개념

인텐트 필터(Intent Filter)는 IntentFilter 클래스의 인스턴스입니다. 인텐트 필터는 주로 암시적 인텐트(implicit intent)를 사용할 때 유용하며, 자바(Java) 코드에서 처리하는 것이 아니라 반드시 AndroidManifest.xml 파일에 직접 선언해야 합니다.

안드로이드 시스템은 실행하려는 인텐트가 어떤 종류인지 미리 파악해야 합니다. 인텐트 필터는 바로 이를 위해 인텐트의 유형과 수행할 액션(Action)에 대한 정보를 시스템에 전달하는 역할을 담당합니다.

인텐트 필터의 3가지 테스트

안드로이드는 인텐트를 실제로 실행하기 전에 다음 세 가지 검사를 순차적으로 수행합니다.

  • 액션 테스트(Action Test) – 인텐트에 지정된 액션이 필터에 선언된 액션과 일치하는지 확인합니다.
  • 카테고리 테스트(Category Test) – 인텐트의 카테고리가 필터에 포함되어 있는지 검사합니다.
  • 데이터 테스트(Data Test) – 인텐트에 담긴 데이터의 URI와 MIME 타입이 필터 조건에 맞는지 확인합니다.

아래 예제를 통해 안드로이드에서 인텐트 필터를 실제로 사용하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

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

2단계: 레이아웃 작성 (res/layout/activity_main.xml)

레이아웃 파일에 아래 코드를 추가합니다. 화면 중앙에 버튼 하나를 배치하며, 이 버튼을 클릭하면 액션 정보가 담긴 인텐트가 호출됩니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/buton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="intent filter button" />

</LinearLayout>

3단계: 메인 액티비티 작성 (src/MainActivity.java)

메인 액티비티에 아래 코드를 추가합니다. 버튼을 클릭하면 ACTION_SEND 액션으로 인텐트를 생성하고, MIME 타입을 message/rfc822(이메일)로 지정한 후 수신자 이메일 주소와 제목을 전달합니다.

package com.example.andy.myapplication;

import android.content.Intent;
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);

        final Button button = findViewById(R.id.buton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("message/rfc822");
                intent.putExtra(Intent.EXTRA_EMAIL,
                        new String[]{"contact@tutorialspoint.com"});
                intent.putExtra(Intent.EXTRA_SUBJECT,
                        "Welcome to tutorialspoint.com");
                startActivity(Intent.createChooser(intent, "Choose default Mail App"));
            }
        });
    }
}

위 코드에서는 버튼 클릭 시 ACTION_SEND를 사용해 인텐트를 호출하고 타입을 message/rfc822로 설정했습니다. 그리고 이메일 주소와 제목 메시지를 함께 전달하도록 구성했습니다.

4단계: 매니페스트에 인텐트 필터 선언 (manifest.xml)

매니페스트 파일에 아래와 같이 액션(Action), 카테고리(Category), 데이터(Data)를 선언합니다.

<?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" />
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="message/rfc822" />
            </intent-filter>
        </activity>

    </application>
</manifest>

여기까지 완료했다면 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결한 상태라고 가정하고 진행합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 버튼을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기에 앱의 기본 화면이 표시됩니다.

실행 결과 확인

앱이 실행되면 화면 중앙의 버튼이 나타납니다. 이 버튼을 클릭하면 인텐트에 담긴 데이터를 전송할 앱을 선택할 수 있는 인텐트 선택기(Intent Chooser)가 호출됩니다.

선택기 목록에서 Gmail 앱을 선택해 보겠습니다.

최종 결과를 보면, 인텐트에 담겨 있던 데이터(수신자 이메일 주소, 제목)가 Gmail 앱에 자동으로 채워지는 것을 확인할 수 있습니다. 이처럼 인텐트 필터를 활용하면 특정 액션을 처리할 수 있는 적절한 앱을 시스템이 자동으로 찾아 연결해 줍니다.