Android:预定通知没有显示?

时间:2016-04-12 01:04:14

标签: java android push-notification android-notifications

我基本上试图在预定时间显示每日通知(例如:每天上午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);
        }
 }

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

我在这里做错了什么?我应该在清单上添加任何东西吗?这是我现在唯一的两个实现。提前谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

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

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

最后,您需要以某种方式获取WakeLock以确保即使手机未处于活动状态也会发出Notification。除了自己处理WakeLock之外,还有其他几种选择。 v4支持库中的WakefulBroadcastReceiver class可用于启动Service,您可以从中发信号通知Receiver在完成后释放锁定。或者,如果您不想添加Receiver组件,只需将Service替换为CommonsWareWakefulIntentService class即可。

如果您选择使用WakefulBroadcastReceiver,您可能仍会考虑将Service更改为IntentService,如果它不会执行任何长时间运行的操作,则{ {1}}在工作完成后负责停止。

相关问题