public int onStartCommand(Intent intent, int flags, int startId) {
...
for (int i = 1; i < dayStore.getInt("lessonCount" , 0)+1; i++) {
String lesson = dayStore.getString("Lesson" + i , "null");
String lessonWithoutTime = (lesson.substring(6, lesson.length()-6)).replace(".", "");
String lessonTitleRaw = lessonWithoutTime.split(" ")[0];
String lessonTitle = lessonTitleRaw.replace(".", "");
String startTime = lesson.substring(0, 5);
//---------------------------------------------------
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime.substring(0,2)));
calendar.set(Calendar.MINUTE, 0);
calendar.add(Calendar.MINUTE, Integer.parseInt(startTime.substring(3,5))-5);
Intent notifications = new Intent(this, StartNotification.class);
notifications.putExtra("LessonTitle", lessonTitle);
notifications.putExtra("StartTime", startTime);
PendingIntent pendingNotifications = PendingIntent.getService(this, 0, notifications, 0);
AlarmManager startNotif = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
startNotif.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingNotifications);
}
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
因此,在上面的代碼中,它經歷了一個「for i」循環,它爲每個課程的開始創建一個AlarmManager。當AlarmManager推移它會打開一個名爲「StartNotification」這比讓這樣的通知服務......AlarmManager在通過calendar.getTimeInMillis()設置時沒有關閉。
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.main_icon)
.setContentTitle(lesson)
.setTicker(lesson + " starts in 5 minutes")
.setContentText(lesson + " from " + startTime + " to " + endTime);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
stopSelf();
的問題是,AlarmManager不工作,也可能是與日曆一個問題。因爲當我將其更改爲此startNotif.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, pendingNotifications);
(從calendar.getTimeInMillis
- >System.currentTimeMillis() + 1000
)它工作正常,但只適用於第一次報警。雖然你會認爲所有的(在這種情況下是5)警報/通知會同時(1000工廠),但只有第一個。
我知道,所有的報警都被設置,因爲我用Log.D:■廣泛。 日曆具有正確的毫秒數,我已經以許多不同的方式檢查過。
這些都是我的權限:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
和服務:
所有你需要一個創建一個PendingIntent
改變線的
<service android:enabled="true" android:name=".Notifications" />
<service android:enabled="true" android:name=".StartNotification" />
...