-
Intent (인텐트) 와 Bundle안드로이드 학습/Android 기술면접 대비 2023. 7. 11. 17:11
차례 : 1) Intent란 2) 2가지 Intent 타입 : Explicit Intents (명시적), Implicit Intents (암시적). 3) IntentFilter 4) PendingIntent 5) Bundle 이란?
1) Intent란?
Intent는 컴포넌트(Activity, Service, BroadCast Receiver)간에 통신을 하기 위한 '메시지 객체' 입니다.
Intent 구성 요소 사이의 통신을 하는 여러가지 방식이 있지만 기본적인으로는 3가지로 나눌 수 있습니다.
Intent 사용되는 곳:
- Activity: startActivity(Intent), startActivityForResult(Intent, requestCode)
- Service: startService(Intent), bindService(Intent)
- Broadcast: sendBroadcast(Intent), sendOrderedBroadcast(Intent), sendStickyBroadcast()
- 외부 앱 호출 : 웹페이지 열기, 전화 걸기 등등
Activity 예제 :
더보기// startActivity(Intent) Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); // startActivityForResult(Intent, requestCode) Intent intent = new Intent(this, SecondActivity.class); int requestCode = 1; startActivityForResult(intent, requestCode);
Service 예제 :
더보기// startService(Intent) Intent intent = new Intent(this, MyService.class); startService(intent); // bindService(Intent) Intent intent = new Intent(this, MyService.class); ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 서비스와의 연결이 설정될 때 호출되는 콜백 메서드 MyService.MyBinder binder = (MyService.MyBinder) service; MyService myService = binder.getService(); // 서비스의 메서드를 호출하거나 작업을 수행할 수 있습니다. } @Override public void onServiceDisconnected(ComponentName name) { // 서비스와의 연결이 해제될 때 호출되는 콜백 메서드 } }; bindService(intent, connection, Context.BIND_AUTO_CREATE);
BroadCastReceiver 예제 :
더보기// sendBroadcast(Intent) Intent intent = new Intent("com.example.MY_ACTION"); sendBroadcast(intent); // sendOrderedBroadcast(Intent) Intent intent = new Intent("com.example.MY_ACTION"); sendOrderedBroadcast(intent, null); // sendStickyBroadcast() Intent intent = new Intent("com.example.MY_ACTION"); sendStickyBroadcast(intent);
외부 앱 호출 예제 :
더보기// 웹페이지 열기 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com")); startActivity(intent); // 전화 걸기 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:123456789")); startActivity(intent);
2) 2가지 Intent 타입 : Explicit Intents (명시적), Implicit Intents (암시적)
Explicit Intents (명시적):
명시적 인텐트는 인텐트에 클래스 객체나 컴포넌트 이름을 지정하여 호출할 대상을 확실히 알 수 있는 경우에 사용합니다. 시작할 컴포넌트 이름을 지정합니다
일반적으로 앱 안에서 구성 요소를 시작할 때 씁니다. 시작하고자 하는 Activity나 Service class의 이름을 알고 있기 때문입니다. 예를 들면 Activity들 간의 정보 전달시 명시적 Intent 사용
Intent intent = new Intent(InputActivity.this, ResultActivity.class); intent.putExtra("my_data", data); startActivity(intent);
Implicit Intents (암시적):
특정 구성 요소의 이름을 대지 않지만, 그 대신 수행할 일반적인 작업을 선언하여 다른 앱의 구성 요소가 이를 처리할 수 있도록 해줍니다. 예를 들어 사용자에게 지도에 있는 한 위치를 표시하고자 하는 경우, 암시적 인텐트를 사용하여 해당 기능을 갖춘 다른 앱이 지정된 위치를 지도에 표시하도록 요청할 수 있습니다.
// 전화 거는 Intent Intent intent = new Intent(Intent.ACTION_DIAL) // google page 트는 Intent Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/"));
(명시적) 이름지정 - 내가 앱에서 만든 것 VS (암시적) 행동지정 - 이미 시스템상에서 만들어져 있는것 정도???
암시적 인텐트 사용 이유 :
암시적 인텐트는 같은 앱 내의 컴포넌트 사이에서만 사용이 가능하다. 다른 어플리케이션 내의 컴포넌트를 사용하기 위해서 암시적 인텐트를 사용 한다.
구글 developer 사이트 인텐트 및 인텐트 필터 정보 이미지 암시적 인텐트가 시스템을 통해 전달되어 다른 액티비티를 시작하는 방법.
- [1] 액티비티 A가 작업 설명이 있는 Intent를 생성하여 이를 startActivity()에 전달합니다.
- [2] Android 시스템이 모든 앱에서 해당 인텐트와 일치하는 인텐트 필터를 검색합니다.
- [3] 일치하는 항목을 찾으면, 시스템이 해당 액티비티의 onCreate() 메서드를 호출하여 이를 Intent에 전달하고, 일치하는 액티비티(액티비티 B)를 시작합니다.
3. IntentFilter
인텐트 필터(IntentFilter)는 컴포넌트가 수신하려는 인텐트 유형을 지정하는 매니페스트 파일의 표현식이다.
안드로이드 시스템 내부에선 수많은 앱들에 의해 수많은 인텐트들이 발생한다. 이 중 자신에게 필요한 인텐트만을 받기 위해 인텐트 필터가 있는 것이다.
- 인텐트 필터는 암시적 인텐트 실행을 위해 필요한 요소다.
- 사용할 인텐트가 여러 종류면 그 개수만큼 인텐트 필터를 매니페스트에 만들어야 한다.
IntentFilter 예:
더보기1. 시작하는 Android Activity도 intent filter로 지정한다.
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
2. Broadcast Receiver에서도 특정 알림은 intent filter로 지정해줘야 받을 수 있다.
<receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BATTERY_LOW" /> </intent-filter> </receiver>
4. PendingIntent
Intent를 가지고 있는 클래스로, 기본 목적은 외부 애플리케이션의 권한을 허가하여 가지고 있는 Intent를 마치 본인 앱의 프로세스에서 실행하는 것처럼 사용하는 것이다.
다른 앱을 사용중에 Intent를 사용한 Notification을 클릭했을때 동작을 안함. 그래서 PendingIntent를 통해 다른 프로세스 (앱) 에게 권한을 허가하여 Intent 를 마치 본인 앱에서 실행되는 것처럼 사용하게 하는 것이다. 때문에 특정 시점에 Intent 가 무조건 수행될 수 있도록 보장되는 것이다.
사용 예:
- Notification (푸시알림) 으로 Intent 작업 수행시 사용
- 바탕화면 (런쳐) 위젯에서 Intent 작업 수행 시 사용
- AlarmManager 를 통해 지정된 시간에 Intent 작업 수행시 사용
PendingIntent 예
더보기알림과 PendingIntent
Intent intent = new Intent(this, NotificationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("My Notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true);
PendingIntent가 가장 흔하게 사용되는 것이 알림인 것 같다.
Activity를 지정하고 getActivity와 함께 PendingIntent를 설정 가능하다.
그렇게 설정된 PendingIntent와 함께 setContentIntent() 메소드에 넣는다면 알림 클릭시 원하는 Activity로 이동한다..
5. Bundle 이란?
Bundle은 Map의 형태로 된 데이터 묶음이다. Map 형태라 key - String, value - int, String, boolean 같은 기본 타입부터 Serializable, Parcelable 같은 타입도 올수 있음
Bundle의 사용
1. Activity의 상태 저장 및 복구 (onSavedInstanceState, onRestoreInstanceState)
- Bundle은 데이터 저장 객체로써 상태 저장 및 복구에 사용된다. Activity가 onStop()이 되기 전에 onSavedInstanceState에서 저장할 데이터를 저장시키고, onStart() 이후에 onRestoreInstanceState에서 복구시킨다.
2. Intent의 extras를 이용하여 다른 구성요소 (Activity, Broadcast Reciever 등)에 데이터 전달
- Intent에서는 putExtra메서드를 이용해 데이터를 입력할수 있다. 이떄 입력되는 Extra가 바로 Bundle 객체이다.
- Intent putExtra 함수 내부적으로는 Bundle을 사용함.
Intent와 Bundle의 차이
Intent는 저장이 아닌 전달하는 수단으로의 객체이고 Bundle은 상태/값 등을 저장하기 위한 객체입니다.
'안드로이드 학습 > Android 기술면접 대비' 카테고리의 다른 글
Rxjava (0) 2024.01.05 안드로이드 4대 컴포넌트 (0) 2023.08.13 AAC - Databinding (0) 2023.06.21 안드로이드 Context (0) 2023.06.16 Jetpack - AAC (0) 2023.06.13