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

Android 알림을 탭했을 때 마지막 활동(Activity)을 여는 방법

이 튜토리얼에서는 Android 알림(Notification)을 탭했을 때 앱의 마지막 활동(Activity)을 여는 방법을 단계별로 살펴봅니다. 핵심은 PendingIntent를 구성할 때 인텐트 플래그를 적절히 설정하여, 이미 실행 중인 앱의 기존 작업 스택을 재사용하도록 만드는 것입니다.

1단계 — 새 프로젝트 만들기

Android Studio에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.

2단계 — activity_main.xml 레이아웃 작성

다음 코드를 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: 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 :padding = "16dp"
   tools :context = ".MainActivity" >
   <Button
      android :id = "@+id/btnCreateNotification"
      android :layout_width = "0dp"
      android :layout_height = "wrap_content"
      android :text = "Create notification"
      app :layout_constraintBottom_toBottomOf = "parent"
      app :layout_constraintEnd_toEndOf = "parent"
      app :layout_constraintStart_toStartOf = "parent"
      app :layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

3단계 — MainActivity.java 코드 작성

다음 코드를 src/MainActivity.java 파일에 추가합니다. 여기서 중요한 부분은 인텐트에 ACTION_MAINCATEGORY_LAUNCHER를 설정하고, FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_SINGLE_TOP 플래그를 지정하는 것입니다. 이렇게 하면 알림을 탭했을 때 새로운 활동이 시작되지 않고, 이미 열려 있는 마지막 활동이 화면에 표시됩니다.

package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Context ;
import android.content.Intent ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
import android.view.View ;
import android.widget.Button ;
public class MainActivity extends AppCompatActivity {
   public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
   private final static String default_notification_channel_id = "default" ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
      btnCreateNotification.setOnClickListener( new View.OnClickListener() {
         @Override
         public void onClick (View v) {
            Intent notificationIntent = new Intent(MainActivity. this, MainActivity. class );
            notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;
            notificationIntent.setAction(Intent. ACTION_MAIN ) ;
            notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP );
            PendingIntent resultIntent = PendingIntent. getActivity (MainActivity. this, 0 , notificationIntent , 0 ) ;
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id )
               .setSmallIcon(R.drawable. ic_launcher_foreground )
               .setContentTitle( "Test" )
               .setContentIntent(resultIntent)
               .setStyle( new NotificationCompat.InboxStyle())
               .setContentText( "Hello! This is my first push notification" ) ;
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE );
            if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
               int importance = NotificationManager. IMPORTANCE_HIGH ;
               NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
               mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
               assert mNotificationManager != null;
               mNotificationManager.createNotificationChannel(notificationChannel) ;
            }
            assert mNotificationManager != null;
            mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
         }
      }) ;
   }
}

핵심 포인트 정리

  • FLAG_ACTIVITY_CLEAR_TOP: 대상 활동이 이미 작업 스택에 있는 경우, 그 위에 쌓인 활동들을 모두 제거하고 해당 활동을 화면 앞으로 가져옵니다.
  • FLAG_ACTIVITY_SINGLE_TOP: 대상 활동이 이미 최상위에 있다면 새 인스턴스를 만들지 않고 기존 인스턴스를 재사용합니다.
  • ACTION_MAIN + CATEGORY_LAUNCHER: 일반적인 런처 실행 방식과 동일하게 동작하도록 하여, 앱의 기존 작업(task)에 자연스럽게 연결됩니다.

4단계 — AndroidManifest.xml 수정

다음 코드를 androidManifest.xml 파일에 추가합니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package = "app.tutorialspoint.com.notifyme" >
   <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>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 활동 파일 중 하나를 연 다음, 도구 모음에서 Run 아이콘을 클릭하세요. 옵션 목록에서 모바일 기기를 선택하면, 연결된 실제 기기에 앱이 설치되어 기본 화면이 표시됩니다.

앱에서 Create notification 버튼을 누르면 알림이 생성되고, 상태 표시줄에 알림이 나타납니다. 이때 홈 버튼을 눌러 앱을 백그라운드로 보낸 후 알림을 탭하면, 새로운 활동이 시작되는 것이 아니라 마지막으로 열려 있던 활동이 그대로 화면에 표시되는 것을 확인할 수 있습니다.

Android 알림을 탭했을 때 마지막 활동(Activity)을 여는 방법