2017-07-08 88 views
-1

我需要在某個時間間隔內設置鬧鐘。爲了實現它,我寫道:鬧鐘管理器在Android中不工作

TestFragment類

private void setupAlarmManager(){ 
    AlarmManager manager = manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); 
    Intent alarmIntent = new Intent(getContext(), AlarmReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i, alarmIntent, PendingIntent.FLAG_ONE_SHOT); 
    manager.set(AlarmManager.RTC_WAKEUP,1499510100000L, pendingIntent); 
    manager.set(AlarmManager.RTC_WAKEUP,1499510220000L, pendingIntent); 
} 

AlarmReceiver類

public class AlarmReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show(); 
} 

}

我把調試點Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();但什麼都沒有發生。

下午4 = 1499510100000L 16:03 = 1499510220000L

我到底做錯了什麼?此外,我想在onReceive方法中添加本地通知。

+0

'4PM = 1499510100000L 4:03 PM = 1499510220000L ** **錯誤**。這些值是*毫秒*警報管理器在運行時應該等待。它**不是時間值**。順便說一句,1499510100000相當於大約'47年半'。您可能不想等很長時間才能看到您的鬧鐘是否會觸發...;) –

+1

1499510100000L來自哪裏?改用日曆。 –

+0

@Rotwang @Mehran該值可能是錯誤的。我會檢查它,但這些值來自數據庫,它使用'Java.Util'時間庫存儲以毫秒爲單位的時間。我不能在這裏使用'new Date()。getTime()'而不是'Calendar'嗎? –

回答

1

您應該使用Calendar對象設置鬧鐘時間。

對於在下午4點報警,你可以這樣做:

Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 16); 
calendar.set(Calendar.MINUTE, 0); 
calendar.set(Calendar.SECOND, 0); 
calendar.set(Calendar.MILLISECOND,0); 

然後您設置AlarmManager,你已經做了,但最後一行使用:

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 

也許你想使用重複報警或甚至是Handler

如果是這樣你應該訪問:https://developer.android.com/training/scheduling/alarms.html

+0

這些值來自數據庫,它使用'Java.Util'時間庫存儲以毫秒爲單位的時間。我不能在這裏使用'new Date()。getTime()'而不是'Calendar'嗎?讓我們以毫秒爲單位獲得兩次(可能更多)。 –

+0

因爲我已經有一個毫秒的日期,日曆也會做同樣的事情 –