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

Android 앱에서 EditText가 포함된 커스텀 푸시 알림 만드는 방법

이 튜토리얼에서는 Android 알림 안에 텍스트를 직접 입력할 수 있는 EditText를 삽입하는 방법을 단계별로 소개합니다. RemoteViews를 활용하면 시스템 기본 알림 레이아웃 대신 직접 디자인한 커스텀 레이아웃을 알림에 적용할 수 있어, 사용자에게 더 풍부한 인터랙션 경험을 제공할 수 있습니다.

프로젝트 준비하기

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 파일에 아래 코드를 추가합니다. 이 레이아웃은 알림에 실제로 표시될 커스텀 UI로, 앱 아이콘을 보여주는 ImageView, 제목을 나타내는 TextView, 그리고 사용자 입력을 받을 EditText로 구성되어 있습니다.

<? 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" />
   <EditText
      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 = "Enter something..."
      android :inputType = "text"
      android :textSize = "14sp" />
</RelativeLayout>

4단계 — MainActivity 코드 작성

src/MainActivity에 아래 코드를 추가합니다. RemoteViews 객체로 커스텀 레이아웃을 알림에 설정하는 것이 핵심입니다. 또한 Android 8.0(Oreo) 이상에서는 반드시 알림 채널(NotificationChannel)을 생성해야 정상적으로 알림이 표시되므로, SDK 버전을 확인하는 분기 처리가 포함되어 있습니다.

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()) ;
   }
   public void createNotification (View view) {
      RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ;
      NotificationManager 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) ;
      }
      assert mNotificationManager != null;
      mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
   }
}

5단계 — AndroidManifest.xml 설정

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

Android 앱에서 EditText가 포함된 커스텀 푸시 알림 만드는 방법