본문 바로가기

AOSP

AOSP) 안드로이드 개발 기본 이해

AOSP를 개발을 하기 이전 안드로이드 애플리케이션의 핵심 구조와 동작 방식을 결정한다는 Activities, Intents, layouts, Anrdoid app lifecycle 개념들을 우선적으로 공부하려고 합니다. 각 개념들이 무엇인지 어떤 역활을 하는지 알아 보도록 하겠습니다.

Activity

activity는 안드로이드 애플리케이션의 주요 사용자 인터페이스 요소를 담당하는 요소입니다. 

Activity를 이루는 구성요소

activity는 클래스 파일(Java, Kotlin)과 XML 파일로 구성되어 있습니다.

XML

XML 파일 내에서 UI 요소를 정의할 수 있습니다. 예를 들어 버튼, 텍스트뷰, 이미지를 생성하고 각 UI 컴포넌트의 세부 요소들을 정의할 수 있습니다.

클래스 파일(Java, Kotlin)

클래스 파일은 XML파일에서 정의된 UI 컴포넌트들을 클래스 파일 상에서 변수와 연결 시켜 컴포넌트의 동작을 제어할 수 있습니다.

AndroidManifest.xml

그리고 생성된 activity는 ActivityManifest.xml에서 관리됩니다. 예를 들어, 특정 activity를 첫 화면으로 설정하고 싶을때는 activity 태그 안 속성 내에 해당 activity를 시작 activity라고 설정하는 태그를 추가하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test1"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.Test1">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

AndroidManifest.xml은 activity뿐만 아니라 주요 컴포넌트 Service, BroadcastReceiver, ContentProvider등을 정의하고 애플리케이션의 구조를 시스템에 알리는 역활을 합니다.

Intent

intent는 activity, service 등 다양한 컴포넌트 간의 통신을 가능하게 해주는 메시지 객체입니다. 뿐만 아니라 다른 앱의 컴포넌트를 호출하는데도 사용됩니다.

intent의 종류

explicit intent(명시적 intent)

명시적으로 intent 객체를 수신할 대상을 표시하는 것

implicit intent(암시적 intent):

수신자를 표시하지 않고, 특정 작업을 표시하여 시스템이 해당 작업을 수행할 수 있는 컴포넌트를 찾아 수행하게 하는 방식

activity간 통신 예시코드(명시적 intent)

// MainActivity.java
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("message", "Hello from MainActivity");
startActivity(intent);

MainActivity파일에서 intent 객체를 생성해줍니다. 생성하는 과정에서 전달받을 activity를 명시해줍니다.

생성한 intent에 키값과 키값과 맵핑할 데이터를 입력해줍니다.

이후 startActivity() 메소드를 통해 intent 객체 생성 시 두번째 인자로 받은  activity를 화면 상에 보여주게됩니다.

 

// SecondActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    // MainActivity로부터 전달된 데이터 받기
    Intent intent = getIntent();
    String message = intent.getStringExtra("message");

    // 받은 데이터를 TextView에 표시
    TextView textView = findViewById(R.id.textView);
    textView.setText(message);
}

MainActivity로부터 SecondActivity를 화면에 표시하게 하였음으로 해당 엑티비티는 화면에 표시가 됩니다.

이후 송신자로부터 전달받은 데이터받고 키값에 맵핑된 데이터를 화면에 표시한다.

웹 페이지 열기(암시적 intent)

// MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 웹 페이지를 열기 위한 암시적 Intent 생성
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://www.example.com"));

        // 암시적 Intent를 처리할 수 있는 Activity가 있는지 확인하고, 없다면 사용자에게 알림
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            // Intent를 처리할 수 있는 Activity가 없는 경우 사용자에게 알림
            // 예를 들어, Toast 메시지를 사용할 수 있습니다.
        }
    }
}

명시적 intent와 달리 암시적 intent는 intent를 수신하는  component를 생성 시에 명시하는것이 아닌 컴포넌트가 수행할 수 있는 "특정 작업"을 명시하게 됩니다. 이때 자바에서는 "특정 작업"을 표현하기 위해 Intent클래스 상수를 통해 표현합니다. 시스템은 해당 작업을 수행할 수 있는 컴포넌트를 찾아서 특정 컴포넌트가 해당 작업을 수행하게 합니다.

 

만약 특정 작업을 수행할 수 있는 컴포넌트가 존재하지 않는다면, intent는 null을 반환합니다.

 

layout

layout은 애플리케이션의 사용자 인터페이스를 구성하는 요소들의 위치와 크기를 정의하는 방식 또는 컨테이너입니다. 

간단히 말해 UI들을 어떻게 배치, 정렬을 할지 정하는 요소입니다. layout은 activity를 구성하는 xml 파일 내에서 정의가 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

</LinearLayout>

위에 코드처럼 UI 컴포넌트들을 배치, 배열하는 요소를 layout이라고 합니다.

 

Anrdoid app lifecycle

app lifecycle는 activity, fragment 등 컴포넌트의 생성, 시작, 일시정지, 재개, 종료 등 상태변화를 관리하는 일련의 콜백 메소드입니다.

lifecycle 관련 메소드

onCreate():     activity가 처음 생성되었을때 호출되는 메소드

onStart():       사용자에게 activity가 visible 상태일때 호출되는 메소드

onResume():  activity가 사용자와 상호작용을 하려고 할때 호출되는 메소드

onPause():     activity가 visible 상태이지만 사용자와 상호작용할 수 없을때 호출되는 메소드

onStop():       activity가 invisible 상태가 된 순간 호출되는 메소드

onRestart():   activity가 멈춘 이후 다시 시작하기 전 호출되는 메소드

onDestroy():   activity가 destroy가 되기 전에 호출 되는 메소드

\

Activity running -> onPause()

foreground에 있던 앱이 background에 이동,  activity가 visible 상태이긴 하지만 사용자와 상호작용할 수 없는 상태가 되는 순간  onPause()메소드가 호출이 된다.

onPause() -> onResume()

사용자가 pause 상태에 있는 activity로 돌아가는 순간 onResume() 메소드가 호출된다.

onPause(), onStop()-> App process killed

background에 존재하는 activity를 우선순위가 높은 앱들이 메모리가 필요한 순간 종료 시키는 순간

onPause() -> onStop()

사용자와 상호작은 못하지만 visible 상태인 activity가 결국 invisible 상태가 되는 순간 onStop() 메소드가 호출된다.

App process killed -> onCreate()

종료된 activity가 다시 생성될때  onCreate() 메소드가 생성이 된다.

onStop() -> onDestroy()

invisible 상태인 activity가 작업을 끝내거나 시스템에 의해 종료가 되는 순간 onDestroy() 메소드가 호출된다.

onStop() -> onRestart()

invisible 상태인 activity가 다시 visible 상태로 돌아오는 순간 onRestart() 메소드가 호출된다.

참조

https://developer.android.com

 

Android 모바일 앱 개발자 도구 - Android 개발자  |  Android Developers

Discover the latest app development tools, platform updates, training, and documentation for developers across every Android device.

developer.android.com

 

https://www.javatpoint.com/android-life-cycle-of-activity

 

Android Activity Lifecycle - javatpoint

Android Activity Lifecycle with examples of Activity and Intent, Fragments, Menu, Service, alarm manager, storage, sqlite, xml, json, multimedia, speech, web service, telephony, animation and graphics

www.javatpoint.com