根据一天中的时间更改图像

时间:2014-05-21 06:51:51

标签: java android eclipse class imageview

我想要Google即时应用的功能,就像白天一样,标题是晴天图像,当它变成中午或日落时,图像会变为日落图像,当它出现时夜晚,图像变为夜间图像,而早晨图像则相同。

我试图实现我的背景,这也是同样的事情,我该如何实施呢?我已经对此进行了搜索,但答案是针对HTML和网站开发的。

其他大多数是基于时间间隔的,我认为这应该是我应该使用的,但我想要这样的东西。用非技术语言编写

01:00/1am - Morning - Image changes to Morning.png on the imageview (R.id.view).

09:00/9am - Normal - Image changes to Daytime.png on the imageview (R.id.view).

12:00/12pm - Noon - Image changes to Noon.png on the imageview (R.id.view).

19:00/7pm - Night - Image changes to Noon.png on the imageview (R.id.view).

我如何才能实现类似的目标?

2 个答案:

答案 0 :(得分:0)

我建议你写一个有listen方法的类。必须定期调用此侦听方法,该方法检查时间并在活动级别上引发自定义事件(您可以在此处使用接口)。您可以使用Timer和TimerTask或CountdownTimer来调用。

答案 1 :(得分:0)

这项工作的最佳人选是AlarmManager

让我们假设您只需要在Activity运行时更改背景。 您可以在创建活动时设置闹钟:

private PendingIntent pi=null;
private AlarmManager mgr=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mgr=(AlarmManager)getSystemService(ALARM_SERVICE);
    pi=createPendingResult(ALARM_ID, new Intent(), 0);
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}

PERIOD(ms)是我们想要获得控制的频率(onActivityResult)。 createPendingResult(ALARM_ID, new Intent(), 0);行创建一个可以在您的Activities onActivityResult方法中捕获的Intent:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == ALARM_ID) {
      // This is where you check the time and change your background!
   }
}

您还需要在onDestroy中取消闹钟:

@Override
public void onDestroy() {
    mgr.cancel(pi);
    super.onDestroy();
}

要检查日期是否在特定时间间隔内,您可以使用:

boolean isWithinRange(Date testDate) {
    return testDate.getTime() >= startDate.getTime() &&
             testDate.getTime() <= endDate.getTime();
}