TOP
본문 바로가기
[Java]/Java Android

[Android] 인텐트(Intent) - 1: 명시적 인텐트

by 기록자_Recordian 2025. 4. 30.
728x90
반응형
이전 내용
 

[Android] 위젯 - 평점 (RatingBar)

이전 내용 [Android] 컴파운드 버튼 3 - 토글 버튼이전 내용 [Android] 컴파운드 버튼 2 - 라디오 버튼이전 내용 [Android] 컴파운드 버튼 1 - 체크 박스이전 내용 [Android] 이벤트 리스너 예제이전 내용 [Andro

puppy-foot-it.tistory.com


인텐트

 

인텐트: 안드로이드 구성 요소인 액티비티, 서비스, 브로드캐스트 리시버 등이 작업을 요청하거나 통신할 때 사용하는 객체로, Android 애플리케이션 간의 상호작용을 가능하게 하는 메커니즘이다. 인텐트를 사용하여 다른 액티비티를 시작하거나 서비스를 요청할 수 있으며, 데이터 전송도 가능하다.

 

[인텐트 용도]

  • 액티비티 시작: 인텐트 객체를 startActivity() 메소드에 전달하면 새로운 액티비티 작업 수행
  • 서비스 시작: 인텐트 객체를 startService() 메소드에 전달하면 새로운 서비스를 시작하며, 기존 서비스에 필요한 요청을 보낼 수도 있음.
  • 브로드캐스트 전달: 인텐트 객체를 sendBroadcast() 메소드에 전달하면 브로드캐스트 리시버에 메시지 보냄.

[인텐트 유형]

  • 명시적 인텐트: 정보를 전달할 때 클래스 객체나 구성 요소 이름을 지정하므로 호출할 대상을 확실히 알 수 있음.
  • 암시적 인텐트: 호출할 대상의 속성은 지정하지만, 호출할 대상이 달라질 수 있음.

구성 요소 실행 시 명확한 대상을 알고 있는 경우 : 명시적 인텐트

대상을 명확히 알 수 없는 경우: 암시적 인텐트


명시적 인텐트로 화면 전환하기
: 액티비티 이동

 

Q. 버튼을 누르면 다른 화면으로 넘어가고, 변경된 화면에서 초기 화면으로 넘어오는 기능 구현하기

 

이를 위해서는

  • Java 폴더에 Activity 를 하나 더 만들어야하고, (총 2개의 액티비티 파일)
  • res/layout 폴더에 layout1.xml, layout2.xml 파일을 두 개 생성 (총 2개의 layout.xml 파일) ▶ layout1 을 만들지 않고, main에다 써도 된다. 추후 Main 액티비티에서 코드 수정
  • res/drawable 폴더에 이미지를 넣어줘야 한다.
  • manifests 폴더의 AndroidManifests.xml 파일에 </application> 위에 아래 코드 추가
<activity android:name=".Activity2" />

 

[layout.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="여기는 액티비티1 입니다." />

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이미지 표시 액티비티 열기"/>

</LinearLayout>

 

[layout2.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="여기는 액티비티2 입니다" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="363dp"
        android:layout_height="418dp"
        android:src="@drawable/pic3" />

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="닫기" />

</LinearLayout>

 

[MainActivity.java]

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout1);
        Button b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        Activity2.class);
                startActivity(intent);
            }
        });

    }
}
  • Button b = (Button) findViewById(R.id.Button01);: findViewById 메서드를 사용하여 XML 레이아웃에서 ID가 Button01인 버튼을 찾아 b 변수에 할당
  • Intent intent = new Intent(MainActivity.this, Activity2.class);: Intent 객체를 생성하여 현재 액티비티(MainActivity)에서 목표 액티비티(Activity2)로 전환할 준비. 이 인텐트를 통해 Activity2를 시작할 수 있다.
  • startActivity(intent): 생성한 인텐트를 사용하여 Activity2를 시작한다. 이 메서드를 호출하면 새로운 액티비티가 스택에 쌓이고 사용자에게 표시
※ 액티비티 스택: Android 애플리케이션의 액티비티(Activity)들이 쌓이는 구조.
액티비티는 사용자 인터페이스를 제공하는 컴포넌트로, 사용자가 애플리케이션을 사용할 때 여러 액티비티가 생성되고 종료되며, 이 과정에서 스택 구조가 형성 된다.
액티비티 스택은 후입선출(LIFO, Last In First Out) 원칙을 따른다. 즉, 가장 마지막에 시작된 액티비티가 가장 먼저 종료 된다. 액티비티가 시작되면 스택의 맨 위에 쌓이고, 사용자가 뒤로 가기 버튼을 누르면 맨 위의 액티비티가 종료 된다.

 

 

[Activity2.java]

layout2 레이아웃에서 Button01 버튼을 클릭하면 현재 액티비티가 종료되도록 설정하는 기능을 구현. 따라서 사용자가 버튼을 클릭하면 현재 액티비티가 닫히고, 이전 액티비티로 돌아간다.

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class Activity2 extends AppCompatActivity {
    Button b;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout2);
        b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
}
}
  • finish() 메서드: 현재 액티비티를 종료하는 데 사용

다음 내용

 

728x90
반응형