我注意到有时异步任务无法正常工作,实际上它的doInBackground()方法不会被调用,服务在该活动的后台运行。 例如,当音乐在带有服务的后台运行时,Async任务不会在后台解析XML,因为它的doInBackground在当时不工作,并且进度对话框或progressBar保持旋转状态。当服务在后台运行时,异步任务无法正常工作(doInBackground未执行),Android
我在几篇文章中读到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
// other code and click listeners
}
class GetData extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
// starting the progress Bar
// initializing the Arraylist,Maps etc
}
@Override
protected Void doInBackground(Void... params) {
//parsing the XML here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// stop the ProgressBar
// Updating my UI here
// setting Adapter for ListView
}
}
}
这工作一般正常,但当服务在backgound运行(我的意思是,当播放音乐时在后面挂)。
我没有得到背后这个异步任务问题的确切原因。 在这种情况下mannual线程实现的帮助...... ??
嗯,我认为这个问题是因为“服务在主线程中运行,所以当它运行时,它会阻止我的AsyncTask运行”......所以我认为如果我们可以在后台线程中运行服务,那可以提供帮助。这就是为什么我尝试IntentService在单独的线程中运行服务,但我怀疑...如果IntentService可以运行无限期类似于服务...并且IntentService几次阻止AsyncTask。 所以我不认为它为这类问题提供了100%完美的解决方案。
任何人都可以帮我解决这个问题,并理解完整的场景。
在此先感谢。
是您扩展业务或IntentService – koti 2013-02-15 09:50:20
我使用的服务,为播放音乐背景 – 2013-02-15 09:54:35
异步任务应该工作。你在某个地方犯了错误。 – Leonidos 2013-02-15 09:57:55