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



我想要Google Now应用程序的功能,就像当它是白天的时候,标题是一个阳光明媚的图像,当它变成中午或日落,图像更改为日落图像,当它是晚上的图像更改为夜间图像,同样的早晨的一个。

我想实现我的后台它做同样的事情,我该如何实现呢?我已经搜索了这个,但答案是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).

我怎样才能做到类似的事情?

这个职位的最佳候选人是一个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);行创建了一个Intent,可以被你的Activities onActivityResult方法捕获:

@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();
}

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

最新更新