Android app for changing wallpaper at regular intervals using a timer

I want to create an application that will change the wallpaper of an Android device at regular intervals, say, every hour or so. Currently, in my code, I start the service and use the Timer object. The Timer object will be called at regular intervals and change the wallpaper.

This is the code that I am currently using. Wallpaper is changed only once, and not after that. Please let me know what to do?

public class Wallpaper extends Service {

    Timer mytimer;
    int interval=60000;
    Drawable drawable;
    WallpaperManager wpm;
    int prev=1;

    @Override
    public void onCreate() {
        super.onCreate();
        mytimer=new Timer();
        wpm=WallpaperManager.getInstance(Wallpaper.this);
    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mytimer.schedule(new TimerTask() {
            @Override
            public void run() {

                if(prev==1){
                    drawable = getResources().getDrawable(R.drawable.two);
                    prev=2;
                }
                else if(prev==2){
                    drawable = getResources().getDrawable(R.drawable.three);
                    prev=3;
                }
                else{
                    drawable = getResources().getDrawable(R.drawable.one);
                    prev=1;
                }


                Bitmap wallpaper=((BitmapDrawable)drawable).getBitmap();

                try {
                    wpm.setBitmap(wallpaper);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }, interval);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Also, do I need to use AlarmManager or Handler for this? I am brand new to Android and a bit confused.

+5
source share
2 answers

, . , , , - . Timer.schedule(timertask, initial delay, interval between recurrences);

. myTimer.schedule(object, interval);

+7

Timer class ScheduledFuture

!

private ScheduledFuture mytimer;

//...

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
    mytimer = timer.scheduleWithFixedDelay(new TimerTask() {
        @Override
        public void run() {
            //...
        }
    }, 0, interval, TimeUnit.MILLISECONDS);
    return super.onStartCommand(intent, flags, startId);
}

//...

@Override
public void onDestroy() {
    super.onDestroy();
    if (mytimer != null) {
        mytimer.cancel(true);
    }
    //...
}
0

All Articles