2015-05-02 67 views
0

我希望每天都顯示通知,但通知會不時顯示。到目前爲止,我還沒有弄清楚這種模式。每天通過AlarmManager和服務顯示通知

在我MainActivity#onCreate我執行這個代碼開始吧:

final Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 8); 
calendar.set(Calendar.MINUTE, 0); 
calendar.set(Calendar.SECOND, 0); 
calendar.add(Calendar.DAY_OF_YEAR, 1); 

final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntentForDailyReminderService(context)); 

對於停止AlarmManager我有這樣的代碼(它在用戶改變偏好的唯一執行):

final AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); 
alarmManager.cancel(getPendingIntentForDailyReminderService(context)); 

的功能getPendingIntentForDailyReminderService定義如下:

final Intent intent = new Intent(context, DailyReminderService.class); 
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

這是我的服務類:

public class DailyReminderService extends Service { 
    private static final int NOTIFICATION_ID = 1; 

    @Override 
    public IBinder onBind(final Intent intent) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(final Intent intent, final int flags, final int startId) { 
     final String contentText = this.getString(R.string.daily_reminder_text); 

     final NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
     builder.setContentTitle(this.getString(R.string.app_name)); 
     builder.setContentText(contentText); 
     builder.setSmallIcon(R.drawable.ic_notification_icon); 
     builder.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText)); 

     final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); 
     builder.setContentIntent(pendingIntent); 

     final Notification notification = builder.build(); 
     notification.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL; 

     final NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); 
     notificationManager.notify(NOTIFICATION_ID, notification); 

     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     final NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); 
     notificationManager.cancel(NOTIFICATION_ID); 

     super.onDestroy(); 
    } 
} 

而且我已經註冊在我的清單服務:

<service 
    android:name=".dailyreminder.DailyReminderService" 
    android:enabled="true" 
    android:exported="true"> 

我在做什麼錯?

回答

0

正確的做法是使用BroadcastReceiver而不是Service

如果您從onStartCommand返回START_STICKY,並且從不明確停止該服務,則每次由於資源較少而終止該服務時,操作系統將在稍後有資源時嘗試重新啓動該服務。

+0

所以我在'Service#onStartCommand'中的代碼會進入'BroadcastReceiver#onReceive'? – Niklas

+0

@Niklas是的,大部分。 – tachyonflux