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

Android에서 프로그래밍 방식으로 알림 표시줄의 알림을 제거하는 방법

이 튜토리얼에서는 Android 앱에서 프로그래밍 방식으로 알림 표시줄(Notification Bar)에 표시된 알림을 제거하는 방법을 단계별로 살펴봅니다.

핵심 원리는 간단합니다. 알림을 발행할 때 사용한 고유 ID를 NotificationManager 객체의 cancel() 메서드에 전달하면, 해당 알림이 즉시 표시줄에서 제거됩니다.

1단계 – 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하여 새 프로젝트를 만들고, 프로젝트 생성에 필요한 모든 정보를 입력합니다.

2단계 – activity_main.xml 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼을 클릭하면 알림이 생성되는 구조입니다.

<? 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>

3단계 – custom_notification_layout.xml 작성

res/layout/custom_notification_layout.xml 파일을 생성하고 아래 코드를 추가합니다. 이 레이아웃은 커스텀 알림의 아이콘과 텍스트 등 외형을 정의합니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "https://schemas.android.com/apk/res/android"
   android :id = "@+id/layout"
   android :layout_width = "fill_parent"
   android :layout_height = "96dp"
   android :padding = "10dp" >
   <ImageView
      android :id = "@+id/image"
      android :layout_width = "wrap_content"
      android :layout_height = "fill_parent"
      android :layout_alignParentStart = "true"
      android :layout_marginEnd = "10dp"
      android :contentDescription = "@string/app_name"
      android :src = "@mipmap/ic_launcher" />
   <TextView
      android :id = "@+id/title"
      android :layout_width = "wrap_content"
      android :layout_height = "wrap_content"
      android :layout_toEndOf = "@id/image"
      android :text = "Testing"
      android :textColor = "#000"
      android :textSize = "18sp" />
   <TextView
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_below = "@+id/title"
      android :layout_marginTop = "8dp"
      android :layout_toEndOf = "@+id/image"
      android :hint = "Thi is just testing notification"
      android :inputType = "text"
      android :textSize = "14sp" />
</RelativeLayout>

4단계 – MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. createNotification() 메서드가 알림을 생성하며, removeNotification() 메서드가 cancel()을 호출하여 해당 알림을 제거합니다.

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.RemoteViews ;
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()) ;
   }
   NotificationManager mNotificationManager ;
   int notificationId = 0 ;
   public void createNotification (View view) {
      RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ;
      mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
      mBuilder.setContent(contentView) ;
      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) ;
      }
      notificationId = ( int ) System. currentTimeMillis () ;
      assert mNotificationManager != null;
      mNotificationManager .notify( notificationId , mBuilder.build()) ;
   }
   public void removeNotification (View view) {
      if ( notificationId != 0 )
      mNotificationManager .cancel( notificationId ) ;
   }
}

참고: removeNotification() 메서드를 직접 테스트하려면 activity_main.xml에 android:onClick="removeNotification" 속성을 가진 두 번째 버튼을 추가하면 됩니다. 또한 이 예제에서는 setAutoCancel(true)가 설정되어 있으므로, 사용자가 알림을 탭하면 해당 알림이 자동으로 제거됩니다.

5단계 – 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" >
   <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 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 실행(Run) 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android에서 프로그래밍 방식으로 알림 표시줄의 알림을 제거하는 방법