I am trying to accept socket connections from clients.
But in my AsyncTask
i came across two situations where I'll need to update UI thread. the first case where as soon as socket is connected, it should change the current content view. And 2nd case where I'm receiving constant stream of objects which I'm updating on UI through publishProgress()
.
How do I go about doing so?
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]);
}
}