Din*_*rma 10 service multithreading android android-asynctask intentservice
我注意到有时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();
}
Run Code Online (Sandbox Code Playgroud)
但这对我的情况没有帮助.在上述实施后遇到同样的问题.
在这里,我只提供一些示例代码来了解我在做什么::
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
这通常很好,但是当服务在后面运行时挂起(我的意思是当音乐在后面播放时).
我没有得到异步任务问题背后的确切原因.在这种情况下,mannual线程实现会有帮助吗???
好吧,我认为问题是因为"服务在主线程中运行所以当它运行时,它会阻止我的AsyncTask运行"......所以我认为如果我们可以在后台线程中运行Service那么可以帮助.这就是为什么我尝试使用IntentService在单独的线程中运行服务但是我有疑问......如果IntentService可以无限期地运行,类似于Service ...而且IntentService也会阻止AsyncTask几次.所以我不认为它是这种问题的100%完美解决方案.
任何人都可以帮我解决这个问题并理解完整的场景.
提前致谢.
这是一个提示,我最终如何解决我的问题::
1)我使用IntentService而不是Service,因为Service在mainThread中运行,而IntentService在与mainThread不同的线程中运行,以确保我的后台Service不会影响我当前的任务。另外,我使用 AIDL 在 UI 和后台线程之间进行通信(这已经适用于 Service ,所以这部分没有什么新内容)。
2)我使用无痛线程而不是 AsyncTask ,我在onDestroy()方法中中断线程以确保线程确实无限期地继续。
应用程序似乎比以前的表现要好得多。
希望这也能帮助其他人:)