简体   繁体   中英

Single Android Thread for Multiple Jobs

I would like to have an application which either loads or saves data through a HTTP request, however the data must interact with the UI thread. Ideally, I would like a single thread to use an IF statement on a message to determine if the request is to "load" or "save".

What would be the simplest way of doing this with the smallest amount of code?

Also, do instances of Handlers run on individual threads?

EDIT: This is the code I am using now:

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 halts the debugging and displays, "Source not found" for StrictMode.class

I suppose it's because it's using the Main thread to access the internet although it's running in individual threads.

Any idea.

Handlers do run on individual threads. Check that link. You should also check out AsyncTask .

I would propose submitting the jobs as Runnable to a single-threaded 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...
      }
    });
  }
}

This way, the UI thread will not block whereas you can easily submit a different Runnable for different operations and the ExecutorService will completely take care of keeping it async.

Edit: If you need to interact with the UI, do so before becoming asynchronous and keep the result in final variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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