Android : AlarmManager를 사용하는 방법
-
23-08-2019 - |
문제
20 분 후에 코드 블록을 트리거해야합니다. AlarmManager
설정 중입니다.
누군가 나에게 사용 방법에 대한 샘플 코드를 보여줄 수 있습니까? AlarmManager
Android에서?
나는 며칠 동안 코드를 가지고 놀았으며 작동하지 않을 것입니다.
해결책
"일부 샘플 코드"는 AlarmManager
.
다음은 설정을 보여주는 스 니펫입니다 AlarmManager
:
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
이 예에서는 사용 중입니다 setRepeating()
. 원샷 알람을 원한다면 만 사용합니다. set()
. 초기 매개 변수에서 사용하는 것과 같은 시간 기반으로 알람이 시작될 시간을 제공하십시오. set()
. 위의 예에서는 사용 중입니다 AlarmManager.ELAPSED_REALTIME_WAKEUP
, 내 시간 기반입니다 SystemClock.elapsedRealtime()
.
다음은 더 큰 샘플 프로젝트입니다 이 기술을 보여줍니다.
다른 팁
Android 샘플 코드에는 몇 가지 좋은 예가 있습니다.
.
체크 아웃하는 것은 다음과 같습니다.
- AlarmController.java
- oneshotalarm.java
우선, 당신은 트리거 될 때 알람을들을 수있는 수신기가 필요합니다. AndroidManifest.xml 파일에 다음을 추가하십시오
<receiver android:name=".MyAlarmReceiver" />
그런 다음 다음 수업을 만드십시오
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
그런 다음 알람을 트리거하려면 다음을 사용하십시오 (예 : 주요 활동).
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
.
또는 더 나은 아직, 모든 것을 처리하고 이렇게 사용하는 수업을 만드십시오.
Bundle bundle = new Bundle();
// add extras here..
MyAlarm alarm = new MyAlarm(this, bundle, 30);
이런 식으로, 당신은 한 곳에 모든 것을 가지고 있습니다 (편집하는 것을 잊지 마십시오. AndroidManifest.xml
)
public class MyAlarm extends BroadcastReceiver {
private final String REMINDER_BUNDLE = "MyReminderBundle";
// this constructor is called by the alarm manager.
public MyAlarm(){ }
// you can use this constructor to create the alarm.
// Just pass in the main activity as the context,
// any extras you'd like to get later when triggered
// and the timeout
public MyAlarm(Context context, Bundle extras, int timeoutInSeconds){
AlarmManager alarmMgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarm.class);
intent.putExtra(REMINDER_BUNDLE, extras);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeoutInSeconds);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
// here you can get the extras you passed in when creating the alarm
//intent.getBundleExtra(REMINDER_BUNDLE));
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
당신이해야 할 일은 먼저 예약해야 할 의도를 만드는 것입니다. 그런 다음 그 의도의 보드 인트를 얻으십시오. 활동, 서비스 및 방송을 예약 할 수 있습니다. 활동을 예약하려면 예 : myActivity :
Intent i = new Intent(getApplicationContext(), MyActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),3333,i,
PendingIntent.FLAG_CANCEL_CURRENT);
이 보증인에게 알람 매너를 제공하십시오.
//getting current time and add 5 seconds in it
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
//registering our pending intent with alarmmanager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), pi);
이제 myactivity가 될 것입니다 응용 프로그램이 시작된 5 초 후에 출시 됨, 응용 프로그램이나 장치를 중지하든 수면 상태로 이동하더라도 (rtc_wakeup 옵션으로 인해). 완전한 예제 코드를 읽을 수 있습니다 예약 활동, 서비스 및 방송 #Android
나는 댓글을 달고 싶었지만 <50 rep. 그래서 여기에 간다. 5.1 이상에서 실행 중이고 1 분 미만의 간격을 사용하는 경우 다음과 같습니다.
Suspiciously short interval 5000 millis; expanding to 60 seconds
보다 여기.
AlarmManager에서 서비스를 호출하려는 경우 일부 샘플 코드 :
PendingIntent pi;
AlarmManager mgr;
mgr = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(DataCollectionActivity.this, HUJIDataCollectionService.class);
pi = PendingIntent.getService(DataCollectionActivity.this, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() , 1000, pi);
userpermissions를 요청할 필요가 없습니다.