How to update UI from a Runnable?

99封情书 提交于 2021-02-08 09:16:31

问题


I need to update ui from runnable. My logic goes like below. I start the runnable from onCreate of the fragment lifecycle. And the runnable instance is responsible to request network. The problem is I don`t know how to update the fragment after runnable instance fetched the data from network.

code to start runnable in fragment in CustomFragment.java.

public void onCreate(Bundle savedInstanceState) {
    Log.d(DEBUG_TAG, "onCreate");
    super.onCreate(savedInstanceState);

    accountMgr.requestAccountInfo();

}

code to start runnable in AccountManager.java

/**
 * request Account info from server
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void requestAccountInfo() {
    Account act = getCurrentAccount();
    Thread t = new Thread(new RequestAccountInfoTask(act));
    t.start();
}

/**
 * automatically update Account info, like space usage, total space size, from background.
 */
 class RequestAccountInfoTask implements Runnable {

    private Account account;

    public RequestAccountInfoTask(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);

    }
}

回答1:


runOnUiThread() requires Activity reference. There are alternatives. You don't need Activity reference to your Thread. You can always get UI handler with the main looper. Pass other arguments like your interface to update the fragment upon completion of your task.

class RequestAccountInfoTask implements Runnable {

    private Account account;
    private Handler mHandler;
    public RequestAccountInfoTask(Account account) {
        this.account = account;
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);
        //use the handler
    }
}

Anything you run on the instantiated Handler will be on UI thread.

Of course, using runOnUiThread() is totally reasonable.




回答2:


you can use runOnUIThread method of activity.

here's code may be help you:

class RequestAccountInfoTask implements Runnable {

    private Account account;

    public RequestAccountInfoTask(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // you can update fragment UI at here
                }
            });
        }
    }
}



回答3:


Please take a look at AsyncTask for updating the UI from a thread:

http://developer.android.com/reference/android/os/AsyncTask.html

Here are the highlights from the above link:

Class Overview AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.




回答4:


You Cannot Update UI from runnable. You Need Handler for Updating UI. See this for more info.




回答5:


The UI only can be modified by the thread that create it. In tho most cases is by the UI thread. So you need yo update using runOnUiThread method. Good Luck




回答6:


I know it's a bit different answer. But I want you to see Android Annotations. Which are very easy to use . I use them only for background and Ui thread. Do every task in background thread by writing @Background over your method name. And do all the UI update in UI thread. I advice you to just check it once. http://androidannotations.org/ Thanks And as far as your answer is concern . You can not update your UI from runnable. See the asyn task for updating your Ui.




回答7:


I recommend using an AsynTask or you can just try this

getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(getActivity(), "ON UI Thread", Toast.LENGTH_LONG).show();
                }
            });



回答8:


You can use the event bus to do it - http://square.github.io/otto/ It is pretty simple. Just send event from your Thread when you need to update the UI like this:

...
//in the end of your heavy job:
bus.post(new YourEvent());

and in your Activity create method:

@Subscribe
public void onYourEvent(YourEvent event) {
    //do what you want there
}

by the way, you can pass any data through event, it is your custom class! Please read manual how to set up this lib, register activity for bus. It is very useful and easy-to-use




回答9:


You can create a Runnable that then posts to the main thread. From Google's developer pages on Processes and Threads

This implementation is thread-safe: the background operation is done from a separate thread while the ImageView is always manipulated from the UI thread.

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            // a potentially  time consuming task
            final Bitmap bitmap =
                    processBitMap("image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}


来源:https://stackoverflow.com/questions/27415236/how-to-update-ui-from-a-runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!