-3

how to add timer to change background of an app in an app while it is open ....This is a code that changes the background and imageview but doesn't change it automatically.... how to do it so that this frame refreshes????

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mMainView = inflater.inflate(R.layout.fragment_weather, container, false);

    changebackground = (RelativeLayout)mMainView.findViewById(R.id.weatherbackground);
    celestials=(ImageView)mMainView.findViewById(R.id.celestial);
    temperature = (TextView)mMainView.findViewById(R.id.temperature);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());

    cal.set(Calendar.HOUR_OF_DAY, 6);
    cal.set(Calendar.MINUTE, 00);
    cal.set(Calendar.SECOND, 0);

    long morning_start = cal.getTimeInMillis();

    cal.set(Calendar.HOUR_OF_DAY, 18);
    cal.set(Calendar.MINUTE, 30);
    cal.set(Calendar.SECOND, 0);

    long morning_end = cal.getTimeInMillis();
    long now = System.currentTimeMillis();

    if(now > morning_start && now < morning_end)
    {
        changebackground.setBackgroundResource(R.drawable.day);
        celestials.setImageResource(R.drawable.sun);
    }
    else
    {
        changebackground.setBackgroundResource(R.drawable.night);
        celestials.setImageResource(R.drawable.moon);
    }
    return mMainView;
}
  • where did you set timer? – Hemant Parmar Jan 19 '18 at 07:36
  • https://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java – Julius Hörger Jan 19 '18 at 07:37
  • Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.HOUR_OF_DAY, 6); cal.set(Calendar.MINUTE, 00); cal.set(Calendar.SECOND, 0); long morning_start = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, 18); cal.set(Calendar.MINUTE, 30); cal.set(Calendar.SECOND, 0); long morning_end = cal.getTimeInMillis(); long now = System.currentTimeMillis(); – Sourabh Sarkar Jan 19 '18 at 07:39
  • it is done same way as any other timer task. Just find how to do something by timer – Vladyslav Matviienko Jan 19 '18 at 07:41
  • here it takes the current time if it is 6 am the background changes to morning and if it is 6 pm the background changes to night – Sourabh Sarkar Jan 19 '18 at 07:41

1 Answers1

0

You can do it by define handler in your main activity which will fire action on particular time, Like

Handler mHandler = new Handler();
Runnable mRunnableUpdatePro = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mRunnableUpdatePro);
            mHandler.postDelayed(mRunnableUpdatePro, TIME_TO_UPDATE_BACKGROUND);
//            updateYourPicAndTheameHere();
      }
    };

Also please write following line in your onCreate

mHandler.postDelayed(mRunnableUpdatePro, TIME_TO_UPDATE_BACKGROUND);
Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39