Android updating ui thread elements - best practice?

五迷三道 提交于 2019-12-12 18:49:49

问题


I have an app that shows some measurement values like temperature, speed and so on.

I want to stick more or less to the MVC pattern so I got something that receives the values when they appear (from a bluetooth component) and sorts them to the special value handlers. those are supposed to calculate stuff and so on (speed from geo coordinates and so on) and pass the values to the View component, which extends activity and is supposed to print the values. Some of the value handlers will be in their own thread or maybe the whole value handler thing will be one single thread.

So first I tried "runOnUIThread" but this is not as I want it cause with many values nothing else will happen in the UI thread and it is not in the idea of the MVC pattern.

Then I thought about handlers but I got the problem that I cannot "find" the handler from the other thread so I would have to pass it on and that is a lot of header change I would have to do.

Then I thought about a private class with static methods which could be reachable from everywhere but dunno if that is clever.

What do you suggest and could you give me examples?


回答1:


Have you tried AsyncTask? You can create a class that extends AsyncTask and contains a simple callback interface, something like:

class CalculationTask extends AsyncTask<Integer, Integer> {
...
    public interface Callback{
        void onCalculationComplete(Integer result);
    }
...
}

Now, override doInBackground() method from the AsyncTask and put the program logic for the calculation in it.

@Override
protected int doInBackground(Integer... params){
    makeNeededCalculation();
    ...
}

Once the calculation is complete, the AsyncTask will call its onPostExecute() method. In this method you can refer to your callback interface.

@Override
protected void onPostExecute(Integer result){
    mCallback.onCalculationComplete(result);
}

Then you should create an instance of your AsyncTask in the class that receives the values bluetooth and implement the callback interface there.

new CalculationTask(this, new CalculationTask.Callback(){

    @Override
    public void onCalculationComplete(Integer result){
        mView.setText("The new value is "+result);
    }
}).execute(valueFromBluetooth);


来源:https://stackoverflow.com/questions/21635062/android-updating-ui-thread-elements-best-practice

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