2015-05-02 33 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