Solarex's Blog

我只想过,平平淡淡的生活,欲望啊,请放过脆弱的我

[Training]Best Practices for Background Jobs

| Comments

Best Practices for Background Jobs

These classes show you how to run jobs in the background to boost your application’s performance and minimize its drain on the battery.

Running in a background service

This class describes how to implement an IntentService, send it work requests, and report its results to other components.

Creating a background service

The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface’s responsiveness. Also, an IntentService isn’t affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.

An IntentService has a few limitations:

  • It can’t interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.不能直接与UI交互
  • Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.任务顺序执行
  • An operation running on an IntentService can’t be interrupted.任务不可被打断

However, in most cases an IntentService is the preferred way to simple background operations.

Multithreading in a UI Environment

| Comments

Why do we need multithreading in Android applications?

Let’s say you want to do a very long operation when the user pushes a button.If you are not using another thread, it will look something like this:

1
2
3
4
5
6
7
8
9
((Button)findViewById(R.id.Button01)).setOnClickListener(
             new OnClickListener() {

          @Override
          public void onClick(View v) {
            int result = doLongOperation();
            updateUI(result);
          }
      });

What will happen?The UI freezes. This is a really bad UI experience. The program may even crash.

The problem in using threads in a UI environment

So what will happen if we use a Thread for a long running operation.Let’s try a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
((Button)findViewById(R.id.Button01)).setOnClickListener(
new OnClickListener() {

          @Override
          public void onClick(View v) {

              (new Thread(new Runnable() {

                  @Override
                  public void run() {
                    int result = doLongOperation();
                    updateUI(result);
                  }
              })).start();

          }

The result in this case is that the application crashes.

1
2
3
12-07 16:24:29.089: ERROR/AndroidRuntime(315): FATAL EXCEPTION: Thread-8
12-07 16:24:29.089: ERROR/AndroidRuntime(315): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
12-07 16:24:29.089: ERROR/AndroidRuntime(315): at …Clearly the Android OS wont let threads other than the main thread change UI elements.

But why?Android UI toolkit, like many other UI environments, is not thread-safe.

Dealing With AsyncTask and Screen Orientation

| Comments

A common task in Android is to perform some background activity in another thread, meanwhile displaying a ProgressDialog to the user. Example of these tasks include downloading some data from internet, logging into an application, etc. Implementing an AsyncTask is fairly a simple job, the big challenge is how to handle it properly when an orientation change occurs.