开发者

Android custom daemon UI thread

I have to create custom daemon UI thread which shows dialog if there are any updates on back-end (to make it easier lets assume that dialog should be shown every 1 minute). I have BaseActivity which is parent for every activity in my app. Dialog should be shown at any of my activities. Also I have my custom SSAApplication cl开发者_运维技巧ass which extends Application. So, I want my UI thread to be a static field of SSAApplication class and this thread to be started and stopped with application. I guess Handler should be used in my case, but I don't know how. The problem is that I can't understand how I can show the dialog from this thread. So, could anybody help with my problem?


You can't show dialogs from anywhere except the UI thread. This is actually good news: you would've spent endless time debugging irreproducible problems if you could!

What you have to do is, as you guessed, report back from the background thread to your front-end activities, and let them do the UI work.

Before the background thread starts its work, hand it a callback interface:

public interface SomeListener {
    public void onSomethingDone(Object result);
}

Let's say you want to start this thread, and have it notify you back whenever it has data (as opposed to requesting the data each time). The basic (unabstracted, ugly looking) approach would be this one:

/* In your Activity */

private Handler mHandler = new Handler();

public void startBackgroundWork() {
    new WorkingThread(new SomeListener() {
        public void onSomethingDone(Object result) {

            mHandler.post(new Runnable() {
                public void run() { showMyDialog(result); }
            }

        }    
    }).start();
}

And then, of course

public class WorkingThread extends Thread {
    private SomeListener mListener;

    public WorkingThread(SomeListener listener) {
        mListener = listener;
    }

    public void run() {
        /* do some work */
        mListener.onSomethingDone(result);
    }
}

This way, your thread calls a function that ensures the dialog is shown from the Activity's thread.

You may face other kinds of problems, however. This is not a 100% correct way of dealing with this. See this blog post for more information:

http://blogactivity.wordpress.com/2011/09/01/proper-use-of-asynctask/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜