如何知道android开始一天的时间?

时间:2015-08-05 09:18:08

标签: android datetime android-service android-broadcast

有没有办法检测一天开始或日期或时间的变化(用户未更改,系统更改)。任何BroadCastReciever要做吗?我正在使用服务每小时运行一次,但是耗尽电池。

我的要求是检查当天何时开始(时间变为上午12点)或时间变化(每小时)我想显示notification

3 个答案:

答案 0 :(得分:4)

使用AlarmManager和BroadcastReceiver在您的情况下在指定的时间(例如00小时)创建警报集。每个新的一天你都会收到一个广播。

 private void setAlarm(Calendar targetCal){
     Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
     PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
     AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
     alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
    }

供进一步参考: http://android-er.blogspot.in/2012/05/create-alarm-set-on-specified-time.html

答案 1 :(得分:1)

或者您可以使用ScheduledExecutorService来安排和执行任务http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html

答案 2 :(得分:1)

这很简单。

第1步

使用AlarmManager定期启动BroadcastReceiver ..

private void showNotification() {
    Intent alarmIntent = new Intent(this, NotificationReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 50000, pendingIntent);
}

第2步

onReceive()进行检查,当时间是00小时,创建通知并显示。

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar now = GregorianCalendar.getInstance();

        // This is where you check when you want to show the notification
        if(now.get(Calendar.HOUR_OF_DAY) == 0){
            NotificationCompat.Builder mBuilder = 
                    new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(context.getResources().getString(R.string.message_box_title))
                    .setContentText(context.getResources().getString(R.string.message_timesheet_not_up_to_date));


            Intent resultIntent = new Intent(context, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());
        }
    }
}

第3步

忘记注册自定义BroadcastReceiver是Manifest

<receiver
        android:name="com.example.NotificationReceiver"
        android:process=":remote" />