Android应用程序改变墙纸在使用定时器定期 [英] Android app to change wallpaper at regular intervals using Timer

查看:116
本文介绍了Android应用程序改变墙纸在使用定时器定期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个应用程序,这将改变Android设备的壁纸,在固定的时间间隔,比如每隔一小时左右。目前在我的code,我开始一个服务,并正在使用Timer对象。计时器对象将定期调用,改变墙纸。

I wish to create an app, which would change the wallpaper of the Android device at fixed intervals, say every hour or so. Currently in my code, I start a service and am using a Timer object. The Timer object would be invoked at regular intervals and change the wallpaper.

这是在code我使用目前。墙纸得到后,改变只有一次,没有。请让我知道我该怎么办?

This is the code I am using currently. The wallpaper gets changed only once and not after that. Please let me know what should I 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;
    }
}

另外,我是否需要使用AlarmManager或处理程序来实现这一目标?我是很新的Andr​​oid和有点混乱。

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

推荐答案

看起来你正在使用的计时器错误。如果你想拥有它再次发生,你需要指定一个初始延迟的第二个参数,并且间隔为第三。 Timer.schedule(TimerTask的,初始延迟,复发的间隔);

It looks like you're using the timer wrong. If you want to have it recur, you need to specify an initial delay as the second argument, and an interval as the third. Timer.schedule(timertask, initial delay, interval between recurrences);

请注意:我说的是你调用 myTimer.schedule(对象区间);

Note: I'm talking about your call to myTimer.schedule(object, interval);

这篇关于Android应用程序改变墙纸在使用定时器定期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆