安卓:定时通知不显示?



我基本上是在计划的时间(例如:每天早上7:30)显示每日通知。然而,我实现的代码根本没有显示通知。

我设置时间的活动:

//This method is called by a button onClick method
private void SaveData() {
        //I get the hour, minute and the AM/PM from 3 edittexts
        String hours = hoursBox.getText().toString();
        String minutes = minutesBox.getText().toString();
        String ampm = ampmBox.getSelectedItem().toString();
        if (hours.length() != 0 && minutes.length() != 0 && ampm.length() != 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours));
            calendar.set(Calendar.MINUTE, Integer.parseInt(minutes));
            calendar.set(Calendar.SECOND, 0);
            //calendar.set(Calendar.AM_PM, Calendar.AM);
            Intent intent=new Intent(this, ReminderService.class);
            AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
            PendingIntent pendingIntent=PendingIntent.getService(this, 0,intent, 0);
            manager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),24*60*60*1000,pendingIntent);
        }
 }

提醒服务.java

public class ReminderService extends Service {
    @Override
    public void onCreate()
    {
        Intent resultIntent=new Intent(this, Dashboard.class);
        PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);

        Notification noti_builder= new Notification.Builder(this)
                .setContentTitle("Hello from the other side!")
                .setContentIntent(pIntent)
                .setSmallIcon(R.drawable.helloicon)
                .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        noti_builder.flags |=Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1,noti_builder);
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

我在这里做错了什么?我还应该在清单上添加什么吗?这是我目前仅有的两个实现。提前感谢!

应用程序中使用的任何Service都必须列在清单中。此外,由于您的Service仅由您的应用程序使用,因此建议将exported属性设置为false

例如,在清单中的<application>标签内:

<service android:name=".ReminderService"
    android:exported="false" />

此外,Calendar上的Calendar.HOUR_OF_DAY组件设置24小时时钟上的小时。要使用12小时时钟,请使用Calendar.HOUR,并设置Calendar.AM_PM组件。

最后,您将希望以某种方式获得WakeLock,以确保即使手机未激活,您的Notification也能发出。除了自己交WakeLock,还有其他几个选项可供选择。v4支持库中的WakefulBroadcastReceiver类可用于启动Service,完成后您可以从中向接收器发出释放锁定的信号。或者,如果不想添加Receiver组件,可以简单地用CommonsWareWakefulIntentService类替换Service

如果您选择使用WakefulBroadcastReceiver,如果它不打算执行任何长时间运行的操作,您可能仍然会考虑将Service更改为IntentService,因为IntentService会在工作完成时自行停止。

最新更新