Android: 预定通知没有显示?

Android: Scheduled Notification doesn't show up?

我基本上是在尝试在预定时间显示每日通知(例如:每天 7:30 AM)。但是,我实现的代码根本不显示通知。

我设置时间的Activity:

//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);
        }
 }

ReminderService.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,以确保即使 phone 未激活,您的 Notification 也已发出。除了自己处理 WakeLock 之外,还可以使用其他几个选项。 WakefulBroadcastReceiver class in the v4 support library can be used to start your Service, from which you can signal the Receiver to release the lock when done. Alternatively, you could simply replace your Service with CommonsWare's WakefulIntentService class,如果你不想添加 Receiver 组件。

如果您选择使用 WakefulBroadcastReceiver,您可能仍会考虑将 Service 更改为 IntentService,如果它不会做任何长的 运行 ] 操作,因为 IntentService 负责在其工作完成后自行停止。