2017-02-14 24 views
0

我的應用程序使用AlarmManager。 我試下代碼創建報警AlarmManager不起作用,如果屏幕關閉

public void startAlarm(int timeInterval){ 
    if (timeInterval == -1) 
     return; 
    int id = generateIdAlarmManager(); 
    AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    PendingIntent pendingIntent = getPendingIntent(id, timeInterval * 60000); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
    { 
     final AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(System.currentTimeMillis() + timeInterval * 60000, pendingIntent); 

     manager.setAlarmClock(alarmClockInfo, pendingIntent); 
    } 
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) 
     manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeInterval * 60000, pendingIntent); 
    else 
     manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeInterval * 60000, pendingIntent); 

    SharedPreferences.Editor edit = preferences.edit(); 
    edit.putInt(ALARM_MANAGER_ID_ALARM_CHECK_SMS, id); 
    edit.putInt(ALARM_MANAGER_INTERVAL_CHECK_SMS, timeInterval); 
    edit.putBoolean(ALARM_MANAGER_ENABLE_CHECK_SMS, true); 
    edit.apply(); 
    edit.commit(); 
} 

AlarmManager如果屏幕上工作。如果屏幕關閉AlarmManager不起作用。 我加

<uses-permission android:name="android.permission.WAKE_LOCK"/> 

幫助!

回答

0

您的問題已回答here使用WakeLock對象。在Android Developers約WaveLock

的更多信息:

一個喚醒鎖是一種機制,以表明你的應用程序需要 有設備留任。

0

呼叫

manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),timeIntervalForBroadcast, pendingIntent) 

代替alaramManager的manager.set()方法。

+0

此解決方案不起作用。 我嘗試這樣的代碼 manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),timeInterval * 60000,pendingIntent); – user1854307