繁体   English   中英

Android:排定的通知未显示?

[英]Android: Scheduled Notification doesn't show up?

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

我设定时间的活动:

//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.HOUR_OF_DAY上的部件Calendar上设置一个24小时时钟小时。 要使用12小时制,请使用Calendar.HOUR并设置Calendar.AM_PM组件。

最后,您将希望以某种方式获得WakeLock以确保即使手机未激活也可以发出Notification WakeLock自己动手使用WakeLock ,还有其他一些选择。 v4支持库中的WakefulBroadcastReceiver可用于启动Service ,从中您可以通过信号通知Receiver完成后释放锁定。 另外,如果您不想添加Receiver组件,则可以简单地用CommonsWareWakefulIntentService替换Service

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM