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

안드로이드 인텐트(Intent)란 무엇인가? 개념부터 실전 예제까지

인텐트(Intent)는 화면에서 특정 작업을 수행하기 위한 메시지 객체입니다. 주로 새로운 액티비티를 시작하거나, 브로드캐스트 리시버에 이벤트를 전달하고, 서비스를 시작하며, 두 액티비티 사이에 데이터를 주고받을 때 사용됩니다.

명시적 인텐트와 암시적 인텐트

안드로이드의 인텐트는 크게 두 가지로 나뉩니다.

  • 명시적 인텐트(Explicit Intent) : 시작할 컴포넌트를 클래스 이름으로 직접 지정합니다. 주로 같은 앱 내부에서 다른 액티비티를 호출할 때 사용합니다.
  • 암시적 인텐트(Implicit Intent) : 수행할 동작만 선언하고, 그 동작을 처리할 수 있는 앱을 시스템이 찾도록 합니다. 예를 들어 웹페이지 열기나 전화 걸기 등이 있습니다.

이 글에서는 가장 기본이 되는 명시적 인텐트를 활용해, 첫 번째 액티비티에서 두 번째 액티비티를 시작하는 방법을 단계별로 살펴보겠습니다.

1단계 : 새 프로젝트 생성

Android Studio를 실행한 뒤, File → New Project를 선택하고 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

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 = "Send to another activitys"
       android:id = "@+id/send"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

3단계 : 두 번째 액티비티 레이아웃 작성

res/layout/ 폴더에 새 레이아웃 파일(activity_second.xml)을 생성하고 아래 코드를 추가합니다. 전달받은 데이터를 표시할 TextView 하나를 배치했습니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_centerInParent = "true"
    android:layout_centerHorizontal = "true"
    tools:context = ".SecondActivity">
    <TextView
        android:id = "@+id/data"
        android:textSize = "20sp"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />
</android.support.constraint.ConstraintLayout>

4단계 : MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼을 클릭하면 인텐트를 만들어 SecondActivity를 시작하는 구조입니다.

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);
        Button send = findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent send = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(send);
            }
        });
    }
}

위 코드에서는 startActivity() 메서드를 사용해 새로운 액티비티를 시작합니다. 액티비티를 시작하려면 먼저 새 인텐트 객체를 생성하고, 현재 액티비티와 이동할 대상 액티비티를 다음과 같이 인자로 전달해야 합니다.

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

5단계 : SecondActivity 코드 작성

새로운 액티비티 클래스를 생성하고 src/SecondActivity.java 파일에 아래 코드를 추가합니다. TextView에 안내 문구를 표시하도록 설정했습니다.

package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        TextView data=findViewById(R.id.data);
        data.setText("This is second activity");
    }
}

6단계 : AndroidManifest.xml에 액티비티 등록

모든 액티비티는 반드시 매니페스트에 선언되어야 합니다. AndroidManifest.xml 파일에 아래와 같이 MainActivity와 SecondActivity를 등록합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
    <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>
        <activity android:name = ".SecondActivity"></activity>
    </application>
</manifest>

위 코드에서 두 액티비티는 다음과 같이 선언됩니다. MainActivity에는 LAUNCHER 인텐트 필터가 있어 앱 실행 시 처음 열리는 화면이 됩니다.

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

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 안드로이드 인텐트(Intent)란 무엇인가? 개념부터 실전 예제까지 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시됩니다.

안드로이드 인텐트(Intent)란 무엇인가? 개념부터 실전 예제까지

화면의 버튼을 클릭하면 인텐트에 의해 새로운 액티비티가 시작되는 것을 확인할 수 있습니다.

안드로이드 인텐트(Intent)란 무엇인가? 개념부터 실전 예제까지