Programming Language/JAVA

[Android/Java] 반복 예약 알람 (AlarmManager, Broadcast Receiver, Service)

노마딕 2020. 5. 20. 22:57
반응형

Activity - BroadcastReceiver - Service로 이어지는 과정을 이해하는 것이 중요하다.

4대 앱 구성요소(App Component) 중 3가지를 한번에 이용하는 과정이다.

[https://developer.android.com/guide/components/fundamentals?hl=ko]

 

 

1. MainActivity에서 AlarmManager를 이용하여, 특정시간(Calendar)에 AlarmBroadcastReceiver로 Intent한다.

(setInexactRepeating을 통해 반복주기를 설정할 수 있다)

 

2. AlarmBroadcastReceiver에서 AlarmIntentService로 Intent한다.

 

3. AlarmIntentService에서 푸시알람이 실행된다.

 

 

*미리 밝혀두지만 위 방법은 반드시 학습용으로만 이해하는 것이 좋다.

*현재는 Doze모드에서 알람매니저가 제대로 활성화되지 않도록 적용되었기 때문에, 정상 작동을 기대하기 어렵다.

AlarmManager를 활용하는 것이 아닌 FCM을 활용해야한다.

안드로이드 개발자료에서도 AlarmManager 사용 자제를 권고하고, FCM 사용을 제안하고 있다.

 

 

 

[MainActivity.java]

package com.e.test_25;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    private AlarmManager alarmMgr;
    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createNotificationChannel();
        alarmBroadcastReceiver();
    }

    public void alarmBroadcastReceiver() {
        Intent alarmBroadcastReceiverintent = new Intent(this, AlarmBroadcastReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmBroadcastReceiverintent, 0);

        alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        // Set the alarm to start at a particular time
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 21);
        calendar.set(Calendar.MINUTE, 13);

        // With setInexactRepeating(), you have to use one of the AlarmManager interval
        // constants--in this case, AlarmManager.INTERVAL_DAY.
        alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60 * 1000, pendingIntent);
    }

//    API26(Oreo)+ notification 작동을 위해서는 channel을 생성해야 함
    public void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "알림설정에서의 제목";
            String description = "Oreo Version 이상을 위한 알림(알림설정에서의 설명)";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel notificationChannel = new NotificationChannel("channel_id", name, importance);
            notificationChannel.setDescription(description);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
}

 

[AlarmBroadcastReceiver.java]

package com.e.test_25;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmBroadcastReceiver extends BroadcastReceiver {
    public AlarmBroadcastReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent alarmIntentServiceIntent = new Intent(context, AlarmIntentService.class);
        context.startService(alarmIntentServiceIntent);
    }
}

 

[AlarmIntentService.java]

package com.e.test_25;

import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;


public class AlarmIntentService extends IntentService {
    public final int NOTIFICATION_ID = 1001;

    public AlarmIntentService() {
        super("AlarmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        Bitmap mLargeIconForNoti = BitmapFactory.decodeResource(this.getResources(),R.drawable.lottomaker3_logo_512x512);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.lottomaker3_logo_25x25)
                .setLargeIcon(mLargeIconForNoti)
                .setContentTitle("알림 타이틀")
                .setContentText("알림 서브텍스트")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }


}

 

[AndroidManifest.xml]

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.e.test_25">

    <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=".AlarmBroadcastReceiver"
            android:enabled="true">
        </receiver>

        <service
            android:name=".AlarmIntentService"
            android:exported="false" />

    </application>
반응형

'Programming Language > JAVA' 카테고리의 다른 글

변수 variables [Java]  (0) 2020.04.25
배열 Array [Java]  (0) 2020.04.14
반복문 for / for each / while [Java]  (0) 2020.04.14
조건문 if, else, switch [Java]  (0) 2020.04.14
코딩 기본다지기 [Java]  (0) 2020.03.11