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

안드로이드 폰 재부팅 후에도 상태 표시줄 알림 유지하는 방법

개요

이 튜토리얼에서는 안드로이드 기기가 재부팅된 후에도 상태 표시줄 알림이 사라지지 않고 지속되도록 만드는 방법을 알아봅니다. 핵심 원리는 BOOT_COMPLETED 브로드캐스트 리시버를 활용하는 것입니다. 폰이 부팅을 마치면 시스템이 이 브로드캐스트를 전송하고, 이를 수신한 앱이 알림을 다시 생성하여 사용자에게 지속적으로 표시할 수 있습니다.

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"
    android:padding="16dp"
    tools:context=".MainActivity" />

3단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package app.tutorialspoint.com.notifyme;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

4단계: USBStateReceiver(브로드캐스트 리시버) 작성

src/USBStateReceiver.java 파일에 아래 코드를 추가합니다. 이 리시버가 부팅 완료 시점에 알림을 다시 등록하는 핵심 역할을 담당합니다.

package app.tutorialspoint.com.notifyme;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class USBStateReceiver extends BroadcastReceiver {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    boolean connected = true;
    @SuppressLint("UnsafeProtectedBroadcastReceiver")
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, default_notification_channel_id);
        builder.setContentTitle("USB - Notification");
        String action = intent.getAction();
        Log.e("USB", action);
        assert action != null;
        builder.setContentText("Connected");
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) context.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);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }
        assert notificationManager != null;
        if (connected) {
            notificationManager.notify(1, notification);
            connected = false;
        } else {
            notificationManager.cancel(1);
            connected = true;
        }
    }
}

5단계: AndroidManifest.xml 설정

AndroidManifest.xml 파일에 아래 코드를 추가합니다. 여기서 가장 중요한 부분은 RECEIVE_BOOT_COMPLETED 권한 선언과 BOOT_COMPLETED 인텐트 필터 등록입니다. 이 두 가지가 있어야 앱이 부팅 완료 이벤트를 감지할 수 있습니다.

<?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" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <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>
        <receiver android:name=".USBStateReceiver">
            <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

앱 실행 및 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시됩니다.

안드로이드 폰 재부팅 후에도 상태 표시줄 알림 유지하는 방법

마무리 정리

재부팅 후에도 알림을 유지하려면 다음 세 가지 요소가 반드시 필요합니다.

첫째, 매니페스트에 RECEIVE_BOOT_COMPLETED 권한을 선언해야 합니다.
둘째, 브로드캐스트 리시버에 BOOT_COMPLETED 액션 인텐트 필터를 등록해야 합니다.
셋째, 리시버의 onReceive() 메서드에서 알림 채널을 생성하고 알림을 다시 발행해야 합니다.

참고로 안드로이드 8.0(API 26) 이상에서는 알림 채널(Notification Channel) 생성이 필수이므로, SDK 버전을 체크하는 조건문을 통해 하위 버전과의 호환성을 유지하는 것이 좋습니다.