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

안드로이드에서 알림 수신 시 커스텀 알럿 또는 뷰 표시하는 방법

이 예제는 Android에서 알림(Notification)을 수신할 때 커스텀 알럿(Custom Alert)이나 뷰(View)를 화면에 표시하는 방법을 단계별로 설명합니다. 버튼을 눌러 알림을 생성하면, 알림과 동시에 화면에 짧은 커스텀 메시지(Toast)가 나타나도록 구현합니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project로 이동한 후, 새 프로젝트를 만들기 위해 필요한 모든 정보를 입력합니다.

2단계 — res/layout/activity_main.xml 코드 추가

메인 레이아웃 파일에 아래 코드를 추가합니다. 화면 중앙에 "Create notification"(알림 생성) 버튼 하나를 배치하는 구성입니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout 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"
   tools :context = ".MainActivity" >
   <Button
      android :onClick = "createNotification"
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_centerInParent = "true"
      android :layout_margin = "16dp"
      android :text = "Create notification" />
</RelativeLayout>

버튼의 android:onClick="createNotification" 속성 덕분에 버튼을 클릭하면 MainActivity의 createNotification() 메서드가 자동으로 호출됩니다.

3단계 — src/MainActivity.java 코드 추가

메인 액티비티에 아래 코드를 추가합니다. 이 코드는 알림 채널을 생성하고, 알림을 발송한 뒤 화면에 커스텀 알럿(Toast)을 표시합니다.

package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.Toast ;
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 ) ;
      onNewIntent(getIntent()) ;
   }
   public void createNotification (View view) {
      NotificationManager mNotificationManager = (NotificationManager)
      getSystemService( NOTIFICATION_SERVICE ) ;
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
      mBuilder.setContentTitle( "Notify Me" ) ;
      mBuilder.setContentText( "Something important!" ) ;
      mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
      mBuilder.setAutoCancel( true ) ;
      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()) ;
      Toast. makeText (MainActivity. this, "Custom Alert View" , Toast. LENGTH_SHORT ).show() ;
   }
}

코드 핵심 포인트:

  • setContentTitle()setContentText()로 알림의 제목과 내용을 지정합니다.
  • setAutoCancel(true)를 설정하면 사용자가 알림을 탭했을 때 알림이 자동으로 사라집니다.
  • Android 8.0(Oreo, API 26) 이상에서는 반드시 NotificationChannel을 생성해야 하며, 여기서는 중요도를 IMPORTANCE_HIGH로 설정해 헤드업(heads-up) 형태로 알림이 표시되도록 했습니다.
  • 마지막으로 Toast.makeText()를 통해 화면에 "Custom Alert View"라는 커스텀 메시지를 잠깐 보여줍니다.

4단계 — AndroidManifest.xml 코드 추가

매니페스트 파일에 아래 코드를 추가합니다. 진동 알림을 위해 VIBRATE 권한을 선언하고, MainActivity를 런처(Launcher) 액티비티로 등록합니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package = "app.tutorialspoint.com.notifyme" >
   <uses-permission android :name = "android.permission.VIBRATE" />
   <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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 옵션 목록에서 본인의 모바일 기기를 선택하면, 앱이 기기에 설치되고 기본 화면이 표시됩니다.

화면 중앙의 "Create notification" 버튼을 탭하면 상단에 "Notify Me — Something important!" 알림이 나타나고, 동시에 화면 하단에 "Custom Alert View"라는 커스텀 알럿(토스트 메시지)이 짧게 표시되는 것을 확인할 수 있습니다.