繁体   English   中英

Android:在JAVA中的线程上按顺序执行任务

[英]Android: Task sequential on a thread in JAVA

具有接收到BroadcastReceiver动作事件并需要按顺序执行它们的用例。

如下所示,事件1和事件2可以背对背接收。 必须完成Event1的工作,然后再开始Event2的工作。

如何使其顺序?

BroadcastReceiver{

onReceive(){

Event1:
Task1 doing Something different.//Cant run network operations here.

Event2:
Task2 doing Something different.//Cant run network operations here.

}

}

executors.newsinglethreadexecutor()handlerthread是我正在寻找的选项..这样做的任何其他好方法吗?

我有解决方案,但我不知道是否有比这更好的解决方案

至少它有效

在事件中使用Asyntask

 public class Event1 extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... params) { //use your Event 1 methode here return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); //call Event2 Event2 event2=new Event2(); event2.execute(); } } public class Event2 extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... params) { //use your Event 2 methode here return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); //call Event3 Event3 event3=new Event3(); event3.execute(); } } public class Event3 extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... params) { //use your Event3 methode here return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); //everything would come after Event 3 write it here } } 

发现executors.newsinglethreadexecutor()或handlerthread都可以顺序处理任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM