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

Android 알림에 진동과 알림 LED(조명) 활성화하는 방법


이 예제는 Android 알림(Notification)에서 진동과 알림 LED(조명)를 활성화하는 방법을 단계별로 설명합니다.

1단계 – Android Studio에서 새 프로젝트 생성

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

2단계 – activity_main.xml에 코드 추가

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에는 'Create notification'(알림 생성) 버튼이 배치되어 있으며, 이 버튼을 클릭하면 createNotification() 메서드가 호출됩니다.

<?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단계 – 커스텀 알림 레이아웃 추가

res/layout/custom_notification_layout.xml 파일을 생성하고 다음 코드를 추가합니다. 이 레이아웃은 RemoteViews를 통해 알림의 사용자 지정 UI로 사용되며, 앱 아이콘, 제목 텍스트, 입력 필드로 구성됩니다.

<?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에 아래 코드를 추가합니다. 핵심 로직은 다음과 같습니다.

  • NotificationChannel 생성: Android 8.0(오레오, API 26) 이상에서는 알림 채널이 필수이므로 SDK 버전을 확인한 후 채널을 생성합니다.
  • LED 색상 설정: setLightColor() 메서드로 알림 등(LED)의 색상을 지정합니다.
  • 진동 설정: setVibrationPattern()에 진동 패턴 배열({0, 500} – 즉시 시작 후 500ms 진동)을 전달하고, enableVibration(true)으로 진동을 활성화합니다.
  • 중요도 설정: IMPORTANCE_HIGH를 지정하면 헤드업(heads-up) 형태로 눈에 잘 띄게 표시됩니다.
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);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_SECRET);
        long[] VIBRATE_PATTERN = {0, 500};
        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);
            notificationChannel.setLightColor(R.color.colorAccent);
            notificationChannel.setVibrationPattern(VIBRATE_PATTERN);
            notificationChannel.enableVibration(true);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

5단계 – AndroidManifest.xml에 권한 추가

진동 기능을 사용하려면 android.permission.VIBRATE 권한이 반드시 선언되어야 합니다. 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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 기기의 기본 화면이 표시되면 'Create notification' 버튼을 눌러 진동과 LED가 함께 작동하는 알림을 직접 확인할 수 있습니다.

Android 알림에 진동과 알림 LED(조명) 활성화하는 방법