How to use threads for each tabs in android?
I am developing an application which is having four tabs. In each tabs I have implemented each separate functions. I would like to implement threads for each tabs to make the program more efficient. Can anybody suggest the way to implement threads in t开发者_如何学Cabbed activity?
You could put the running function either using the java Thread class or the doInBackground method by extending an AsyncTask class.
Ref: http://developer.android.com/reference/android/os/AsyncTask.html
I am not seeing the advantage to having each tab run in its own thread. The advantage to threading in Android would be to do time consuming work in the background, which would prevent the UI from locking up. What is it that each tab will be doing?
You can have threads to do background work in each tabbed Activity, but if you are planning on updating the UI, it must be done in the 'primary', or UI, thread.
On the android documentation there is a great article about "painless threading" you might wanna try from there. I would recommend not to take an approach for each tab instead try to keep in background those task that might block your UI thread (like downloading or parsing).
Here is a small snipped that might help you
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.adapter = new PersonAdapter(this, R.layout.main_item, new ArrayList<Person>());
setListAdapter(this.adapter);
ListView listView=(ListView)findViewById(R.id.section);
sectionAdapter=new SectionAdapter(this,R.layout.section_item,sections);
listView.setAdapter(sectionAdapter);
//execute the filling section task in background
progressDialog = ProgressDialog.show(MainFeedActivity.this,
"Please wait...", "Retrieving data ...", true);
new SectionTask().execute();
new FeedTask().execute();
}
private class SectionTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
//ProcessInformation Here Background Thread you can do downloading and parsing
}
@Override
public void onPostExecute(Void result){
//Update your UI here [UI Thread]
}
Be careful though there is a AsyncTask limit
精彩评论