用于多个工作的单个Android线程

时间:2012-01-28 21:21:13

标签: java android multithreading task

我希望有一个应用程序通过HTTP请求加载或保存数据,但数据必须与UI线程交互。理想情况下,我希望单个线程在消息上使用IF语句来确定请求是“加载”还是“保存”。

使用最少量的代码执行此操作的最简单方法是什么?

此外,处理程序的实例是否在各个线程上运行?

编辑:这是我现在使用的代码:

Handler doStuff = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what == 1){
                // Load all the information.
                // Get the ID from sharedPrefs
                SharedPreferences details= getSharedPreferences("details", 0);
                String ID = patDetails.getString("id", "error");
                // Load up the ID from HTTP
                String patInfo = httpInc.getURLContent("info.php?no="+AES.encrypt("387gk3hjbo8sgslksjho87s", ID));
                // Separate all the details
                patientInfo = patInfo.split("~");
            }
            if(msg.what == 2){
                // Save the data
            }
        }
    };

Eclipse停止调试并显示StrictMode.class的“Source not found”

我想这是因为它使用主线程来访问互联网,尽管它在各个线程中运行。

任何想法。

2 个答案:

答案 0 :(得分:0)

Handlers在各个线程上运行。检查该链接。您还应该查看AsyncTask

答案 1 :(得分:0)

我建议将作业Runnable提交给单线程ExecutorService

public class SomeClass {
  private ExecutorService execService = Executors.newSingleThreadExecutor();

  public void doSomething() {
    final String someUiData = // retrieve data from UI

    execService.submit(new Runnable() {

      @Override
      public void run() {
        // so something time-consuming, which will be executed asynchronously from the UI thread
        // you can also access someUiData here...
      }
    });
  }
}

这样,UI线程不会阻塞,而您可以轻松地为不同的操作提交不同的RunnableExecutorService将完全保持异步。

编辑:如果您需要与UI进行交互,请在变为异步之前执行此操作并将结果保存在最终变量中。

相关问题