본문 바로가기
안드로이드/개발자 일상

안드로이드 AlarmManager 1-1 (매일 반복적으로 알람 받기)

by 차누감 2020. 4. 2.

AlarmManager과 TimePicker를 이용하여

원하는 시간을 선택하여 반복적으로 알림을 받는 예제를 해보겠습니다.

 

<실행화면> 알람을 맞추고 등록을 누르면 해당 시간에 알람이 나옵니다. (매일 반복)


우선 xml을 작성합니다.

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TimePicker
        android:id="@+id/tp_timepicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:onClick="regist"
        android:text="등록"
        app:layout_constraintBaseline_toBaselineOf="@+id/button2"
        app:layout_constraintEnd_toStartOf="@+id/button2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tp_timepicker" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:onClick="unregist"
        android:text="해지"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/tp_timepicker" />
 
 
 

그리고 이제 정해진 시간에 실행되는 BroadcastReceiver를 상속 받는 클래스를 만듭니다.

Alarm.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.ex_alarm;
 
import android.content.BroadcastReceiver;
import android.content.Context;
 
public class Alarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "알람~!!", Toast.LENGTH_SHORT).show();    // AVD 확인용
        Log.e("Alarm","알람입니다.");    // 로그 확인용
    }
}
 
 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.ex_alarm;
 
 
import android.content.Context;
 
 
public class MainActivity extends AppCompatActivity {
 
    private TimePicker timePicker;
    private AlarmManager alarmManager;
    private int hour, minute;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        timePicker=findViewById(R.id.tp_timepicker);
 
    }// onCreate()..
 
    public void regist(View view) {
 
        Intent intent = new Intent(this, Alarm.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(this0,intent, 0);
    
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            hour=timePicker.getHour();
            minute=timePicker.getMinute();
        }
 
        Calendar calendar = Calendar.getInstance();
 
          // 지정한 시간에 매일 알림
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),  AlarmManager.INTERVAL_DAY, pIntent);
 
    }// regist()..
 
    public void unregist(View view) {
        Intent intent = new Intent(this, Alarm.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(this0, intent, 0);
    }// unregist()..
 
}// MainActivity class..
 
 

 

<추가 정보>
setRepeating 사용 시 안드로이드 롤리팝(5.0) 이상 버전부터는 최소 반복 시간은 1분입니다.

 

AndroidManifest.java에서

  <application>

      <receiver android:name=".Alarm"></receiver> 를 추가해줍니다.

 </application>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.ex_alarm">
 
    <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=".Alarm"></receiver>
    </application>
 
</manifest>
 
 

<실행화면> 알람을 맞추고 등록을 누르면 해당 시간에 알람이 나옵니다. (매일 반복)

19이상 버전에서 AlarmManager를 사용할 경우 내용입니다. 참고하세요.

https://developer.android.com/about/versions/android-4.4?hl=ko#BehaviorAlarms

 

Android 4.4 API  |  Android 개발자  |  Android Developers

API Level: KITKAT) is a new release for the Android platform that offers new features for users and app developers. This document provides an introduction to the most notable new APIs. As an app developer, you should download the Android targetSdkVersion…

developer.android.com

더보기

앱이 AlarmManager를 사용하는 경우...

앱의 targetSdkVersion을 "19" 이상으로 설정하면, set() 또는 setRepeating()을 사용하여 생성하는 알람이 부정확해 집니다.

이제 Android에서는 전원 효율성을 개선하기 위해 모든 앱에서 합리적으로 비슷한 횟수로 발생하는 알람을 함께 일괄 처리하기 때문에, 시스템이 몇 번에 걸치지 않고 한 번에 기기를 깨워 각 알람을 처리합니다.

알람이 정확한 시간과 관련되어 있지 않지만 여전히 특정 시간대(예, 오후 2시~4시)에 알람을 호출하는 것이 중요한 경우, 새 setWindow() 메서드를 사용하여 알람에 대한 "가장 이른" 시간 및 시스템이 알람을 호출해야 하는 가장 이른 시간 이후의 "시간대"를 수락할 수 있습니다.

알람을 정확한 시간에 고정시켜야 하는 경우(예: 캘린더 이벤트 알림), 새 setExact() 메서드를 사용할 수 있습니다.

이러한 정확한 일괄 처리 동작은 업데이트된 앱에만 적용됩니다. targetSdkVersion을 "18" 이하로 설정한 경우, 알람은 이전 버전에서 Android 4.4에서 실행할 때 했던 동작을 계속합니다.

 

setRepeating()에 관한 자료입니다.

https://developer.android.com/reference/android/app/AlarmManager?hl=ko#setRepeating(int,%20long,%20long,%20android.app.PendingIntent)

 

AlarmManager  |  Android 개발자  |  Android Developers

AlarmManager public class AlarmManager extends Object java.lang.Object    ↳ android.app.AlarmManager This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm

developer.android.com

 

댓글