我注意到有时Async任务无法正常运行,实际上它的doInBackground()方法没有被调用,这种情况主要发生在该活动在后台运行任何服务时。
例如,当音乐在带有服务的后台运行时,Async任务不会在后台解析XML,因为它的doInBackground当时不起作用,并且进度Dialog或progressBar一直旋转。
我读过几篇文章,AsyncTask.THREAD_POOL_EXECUTOR可以帮助解决以下问题:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new Test().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new Test().execute();
}
但这对我的情况没有帮助。在上述实施后存在相同的问题。
在这里,我仅提供一些示例代码来了解我在做什么:
public class TestAct extends Activity {
ImageButton play,forward,backward;
private ListView mList;
// many more variables
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
//binding the service here
// start service is called
init();
}
private void init(){
play=(ImageButton)findViewById(R.id.playBtn);
forward=(ImageButton)findViewById(R.id.forward);
backward=(ImageButton)findViewById(R.id.backward);
mList=(ListView)findViewById(R.id.list);
new GetData().execute();
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// calling the play() method of ServiceConnection here
}
});
// adding header to Listview