Hullo,
I have an activity whose layout is made of a single FrameLayout. I have a class that extends View which is then added onto this layout.
I want to continually draw to this view, like in a game loop.
Problem is I’m new to android and this Threading stuff is making no sense..
Can I really not update the layout unless I’m in the main UI thread?
How do I go about initialising Threads? 🙁
EDIT::This is what I’ve come up with, but it doesn’t update my frame with anything.
public class GameFrame extends View
{
private GameThread m_gt;
public GameFrame(Context context, int width int height){
//do some initialisation stuff
}
public GameThread getGameThread(){
if(m_gt != null){
return m_gt;
}else{
m_gt = new GameThread(this);
return m_gt;
}
}
@Override
public void onDraw(Canvas canvas){
//Draw loads of stuff
}
public class GameThread extends AsyncTask<Void, Void, Void>
{
private GameFrame m_gf;
public GameThread(GameFrame gf){
m_gf = gf;
}
@Override
protected void onProgressUpdate(Void... arg0){
System.out.println("Wahoo");
m_gf.invalidate();
}
@Override
protected Void doInBackground(Void... arg0) {
long start, end;
while(some bool){
System.out.println("Threadin'");
publishProgress();
//Fiddle with some values
}
return null;
}
}
}
And then to initialise it in main activity:
private FrameLayout frame;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
...
frame = (FrameLayout) findViewById(R.id.gameframe);
GameFrame gf = new GameFrame(this, width, height);
frame.addView(gf);
gf.getGameThread().execute();
}
Is my understanding of Async correct? Should this work given valid code in onDraw?
I should probably say the print outs “wahoo” and “threading” are being printed out numerous times so something must be happening right. More crucially if it has printed “wahoo” then surely it should next redraw my View…but nothing happens 🙁
You use an AsyncTask
This has two method that allow you to update the main UI before and after the thread has ran
Also as Tom said in the comment, if you want to continue to update the main UI while the asynctask is being ran, check out this You can do this via publishProgress()