2017-03-27 4 views
1
private void startAlarm() { 

    AlarmManager alarmMgr; 
    PendingIntent alarmIntent; 

    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); 
    alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0); 


    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(System.currentTimeMillis()); 
    calendar.set(Calendar.HOUR_OF_DAY, 23); 
    calendar.set(Calendar.MINUTE, 52); 

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
      1000 * 60 * 20, alarmIntent); 

} 

startAlarm() 메소드는 MainActivity 클래스에 있습니다.알람 관리자 안드로이드

다음 코드 23시 52분에서 (onReceive 선언()는 클래스 AlarmReceiver 방법) 축배 및 20 분 간격으로 표시해야 그 후

AlarmReceiver는 브로드 캐스트 리시버를 확장한다.

코드는 오류없이 컴파일되지만 어떤 이유로 토스트를 표시하지 않습니다.

참고 : 코드는 ELAPSED_REALTIME_WAKEUP으로 정상적으로 작동합니다. RTC_WAKEUP에만 문제가 있습니다. 그래서 다른 모든 것들은 정확해야합니다. startAlarm() 메소드 내부에서만 잘못된 것이 있습니다.

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); 
intent.setAction("YourPackageName.YourAction"); 
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0); 

그리고 매니페스트에 :

<receiver android:name=".AlarmReciever"> 
      <intent-filter> 
       <action android:name="YourPackageName.YourAction" /> 
      </intent-filter> 
     </receiver> 

이 문제를 해결해야 당신은 의도 작업을 설정해야처럼

+0

코드가 ELAPSED_REALTIME_WAKEUP에서 제대로 작동합니다. RTC_WAKEUP에만 문제가 있습니다. 그래서 다른 모든 것들은 정확해야합니다. startAlarm() 메소드 내부에서만 잘못된 것이 있습니다. – rayan

답변

1

다음과 같이 일부 수정하여 코드를 사용해 보았습니다.

private void startAlarm() { 

     AlarmManager alarmMgr; 
     PendingIntent alarmIntent; 

     alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); 
     alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0); 


     Calendar calendar = Calendar.getInstance(); 
     calendar.setTimeInMillis(System.currentTimeMillis()); 
     calendar.set(Calendar.HOUR_OF_DAY, 0); 
     calendar.set(Calendar.MINUTE, 2); 

     alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
       1000 * 20, alarmIntent); 
    } 

이 코드는 AlarmManager.RTC_WAKEUP에서 잘 작동합니다. 작동하지 않는 경우 장치를 설치 한 후 장치를 재부팅하십시오. 재부팅이 완료되면 앱을 시작하십시오. 그런 다음 알람이 울리고 20 초 간격으로 알람이 반복적으로 발생합니다.

RTC_WAKEUP과 ELAPSED_REALTIME_WAKEUP의 차이점을 확인할 수도 있습니다. android docs에서 elapsedRealtime은 부팅 후 경과 시간을 밀리 초 단위로 반환하며 RTC는 System.currentTimeMillis() (UTC의 월 시계 시간)에있는 시간을 의미합니다.

0

보인다. 브로드 캐스트 리시버와 함께 사용하려면 고유 한 조치를 취해야합니다.