活动中的onProgressUpdate可以重载吗?

时间:2018-08-30 10:10:04

标签: java android multithreading android-asynctask

我正在尝试接受来自客户端的套接字连接。 但是在我的AsyncTask中,我遇到了两种情况,需要更新UI线程。第一种情况是在连接套接字后立即更改当前内容视图。第二种情况是我收到不断通过publishProgress()在UI上更新的对象流。 我该怎么做?

public class MainActivity extends AppCompatActivity {
   myCustomDrawingView view;
   ....
   ....
   .

   public static MainActivity getContext(){return context;}
   ....
   ..
   public class myCustomDrawingView extends View {
   ..
   ..
   }
   setNewContentView(){
     view = new myCustomDrawingView(this);
     setContentView(view);
   }
}




class ServerTask extends AsyncTask<Void, Action, Void>
{
    private WeakReference<MainActivity> mainActivity;
    private Action action;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mainActivity = new WeakReference<>(MainActivity.getContext());
    }

    @Override
    protected Void doInBackground(Void... voids) {
        ObjectInputStream stream;

        try{
            mainActivity.get().server = new ServerSocket(3107);
            mainActivity.get().socket = mainActivity.get().server.accept();
            stream = new ObjectInputStream(mainActivity.get().socket.getInputStream());

            (mainActivity.get()).setNewContentView(); 
            /*I know this won't work....
              But I want something like this to happen. 
              What are Alternatives?*/

            while(true)
            {
                if(isCancelled()){
                    break;
                }
                action = (Action)stream.readObject();
                publishProgress(action);
            }
        }catch (Exception exception)
        {
            exception.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Action... actions) {
        super.onProgressUpdate(actions);
        ((mainActivity.get()).myCustomDrawingView).draw(actions[0]);
    } 
}

0 个答案:

没有答案