我注意到有時異步任務無法正常工作,實際上它的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