I want to know if I understand correctly how to use synchronized I will write down some pseudo code, which mimics what I am trying to do.
public MyApp extends Application {
public Object mLock = new Object();
private final ArrayList<String> MyList = new ArrayList<String>();
public ArrayList<String> getMyList(){
return MyList;
}
}
private class MyTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... url) {
final ArrayList<String> BgList = MyApp.getMyList();
synchronized (mLock) {
while(somefinishcondition) {
try {
// Get some stuff from the web
BgList.add(newstuff);
mLock.notifyAll();
}
catch (IOException e) {
}
}
}
return null;
}
}
public class DisplayActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewer);
final ArrayList<String> FgList = MyApp.getMyList();
synchronized (mLock) {
while(somecondition) {
mLock.wait();
if(FgList.size()>lastSize) {
n = FgList.size();
for(i=lastSize+1; i<=n ; i++){
Display(Fglist.get(i));
}
lastSize = n;
}
}
}
}
Here is what I think I am doing: I am running a data gathering task in the background, putting the data in a global list. Each time I have new data I notify the DisplayActivity, which goes and displays all new data since the last time.
The AsyncTask locks the data until new data arrives. The DisplayActivity waits on the lock until notified to proceed and display.
Is this right? Is this the usual way?
No, this way you can block the UI thread in
onCreateand you will get Application Not Responding error.Instead, whenever you have some new data, collect the data in
doInBackground()then callupdateProgress()indoInBackground(). This will result inAsyncTask.onProgress()call from the UI thread. InonProgress()do whatever you need with the new data.