【问题标题】:Change an image according to time of day根据一天中的时间更改图像
【发布时间】:2014-05-21 06:51:51
【问题描述】:

我想要谷歌即时应用程序的功能,比如白天时,标题是晴天图像,到中午或日落时,图像变为日落图像,当晚上图像变为夜间图像,和早上的一样。

我正在尝试实现我的背景,它做同样的事情,我必须如何实现呢?我已经对此进行了搜索,但答案是针对 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).

我怎样才能达到类似的效果?

【问题讨论】:

  • 您只希望它用于应用程序还是小部件?应用程序应该很简单:每次打开应用程序时获取当前时间并以编程方式更改图像。一种可能的方法是使用 imageView 作为 Header 进行布局。然后在您的应用程序中获取时间并参考此 imageView,然后只需更改您想要的图片。如果它应该跨时间工作,您可以使用警报管理器来做到这一点。
  • 是的,我认为这对我的应用程序来说是个好主意。

标签: java android eclipse class imageview


【解决方案1】:

这份工作的最佳人选是AlarmManager

假设您只需要在 Activity 运行时更改背景。 您可以在创建 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); 行创建了一个可以在您的活动 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();
}

【讨论】:

  • 感谢您的解释和代码示例,在第二种方法中,我必须使用什么来检查一天中的时间然后显示图像,DateUtils?
  • 我已经更新了我的答案,你可以使用一个简单的 Date 并使用我从stackoverflow.com/a/494203/1803821 得到的方法来检查它是否在你需要的时间间隔内。
  • 感谢您的回答,很有帮助!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多