Android:创建一个定期运行的后台线程并执行UI任务吗? [英] Android: Create a background thread that runs periodically and does UI tasks?

查看:543
本文介绍了Android:创建一个定期运行的后台线程并执行UI任务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道如何执行后台任务,我知道如何执行定期任务(使用后延迟和可运行的句柄),我也知道如何从后台线程(通过处理程序)执行UI任务,但我不是能够执行对UI线程执行某些操作的定期后台任务.

OK, so I know how to do a backround task, I know how to do a periodic task (using handle postdelayed and runnable), I also know how to do UI task from background thread (via handler) but I am not able to execute a periodic background task that does some action on the UI thread.

我试图在每分钟必须执行一次网络呼叫的情况下执行一些后台任务.通话结束后,根据输出,我必须更新UI.我试图做这样的事情

I am trying to execute some background task every minute in which I have to make a network call. After the call is over, depending on the output I have to update the UI. I tried to do something like this

private void DoTask() {
        Thread thread = new Thread() {
            public void run() {
                Looper.prepare();
                final Handler handler = new Handler();
                handler.post(netRunnable);
                Looper.loop();
            }
        };
        thread.start();
}

Runnable netRunnable = new Runnable() {
    @Override
    public void run() {
        handler.getLooper().prepare();
        final Handler handler1 = new Handler(Looper.getMainLooper());
        if ( do background work and check result){
            handler1.post(new Runnable() {
                @Override
                public void run() {
                    //Do UI Task
                }
            });
        }
        handler.getLooper().loop();
        handler.postDelayed(netRunnable, 60000);
    }
}

我了解我的实现可能存在一些基本缺陷,但是我不知道如何正确执行此任务.现在,它给出了错误Only one Looper may be created per thread.我明白了它的意思.但是任何人都可以建议以正确的方式做到这一点.

I understand that there might be some fundamental flaws with my implementation but I do not know how to do this task properly. Right now it is giving the error that Only one Looper may be created per thread.I get what it is trying to say. But can anyone please suggest to do this the right way.

推荐答案

也许更好,创建一个单独的

Maybe you are better of, creating a seperate (Intent)Service and calling it periodically with postDelayed. Create a BroadcastReceiver in your Activity and handle UI changes there.

从其他线程处理UI更改的另一个提示:这是不可能的.因此,您需要调用runOnUiThread. 这里是使用方法

Another hint for handling UI changes from other threads: It is not possible. Therefore you need to call runOnUiThread. Here is how to use it

这篇关于Android:创建一个定期运行的后台线程并执行UI任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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