IntentService的意外行为

use*_*239 5 android

我在我的代码中使用了IntentService而不是Service,因为IntentService在onHandleIntent(Intent intent)中为我创建了一个线程,所以我不必在我的服务代码中创建一个Thead.

我期望同一个IntentSerivce的两个意图将并行执行,因为在IntentService中为每个发明生成一个线程.但我的代码证明了两个意图以顺序方式执行.

这是我的IntentService代码:

public class UpdateService extends IntentService {

    public static final String TAG = "HelloTestIntentService";

    public UpdateService() {
        super("News UpdateService");
    }

    protected void onHandleIntent(Intent intent) {

        String userAction = intent
        .getStringExtra("userAction");

        Log.v(TAG, "" + new Date() + ", In onHandleIntent for userAction = " + userAction + ", thread id = " + Thread.currentThread().getId());

        if ("1".equals(userAction)) {
            try {
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error", e);
            }

            Log.v(TAG, "" + new Date() + ", This thread is waked up.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码调用服务如下:

public class HelloTest extends Activity {

    //@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Intent selectIntent = new Intent(this, UpdateService.class);
        selectIntent.putExtra("userAction",
                "1");

        this.startService(selectIntent);

        selectIntent = new Intent(this, UpdateService.class);
        selectIntent.putExtra("userAction",
                "2");

        this.startService(selectIntent);

    }
}
Run Code Online (Sandbox Code Playgroud)

我在日志中看到了这条日志消息:

V/HelloTestIntentService(  848): Wed May 05 14:59:37 PDT 2010, In onHandleIntent for userAction = 1, thread id = 8
D/dalvikvm(  609): GC freed 941 objects / 55672 bytes in 99ms
V/HelloTestIntentService(  848): Wed May 05 15:00:00 PDT 2010, This thread is waked up.
V/HelloTestIntentService(  848): Wed May 05 15:00:00 PDT 2010, In onHandleIntent for userAction = 2, thread id = 8
I/ActivityManager(  568): Stopping service: com.example.android/.UpdateService
Run Code Online (Sandbox Code Playgroud)

日志显示第二个intent等待第一个意图完成并且它们位于同一个线程中.

有什么我误解了IntentService.要使两个服务意图并行执行,我是否必须用服务替换IntentService并在服务代码中自己启动一个线程?

谢谢.

Eno*_*Eno 9

意图排队是使用IntentService的重点.


小智 7

对IntentService的所有请求都在单个工作线程上处理,并且一次只处理一个请求.如果你想并行完成两个任务,我认为你需要在Service启动后使用Service并为每个任务创建线程.

至于AsyncTask,有一个用于处理所有任务的线程池.如果您的任务编号超过了线程池大小,则其中一些AsyncTasks需要等到池中的线程可用.但是,线程池大小在不同平台版本中更改.

这是我的测试结果:

  • Android 2.2:线程池大小= 5
  • Android 1.5:线程池大小= 1


Mat*_*att 6

据我所知,IntentService有一个处理程序线程,每个intent在该线程中排队.完成所有排队的意图后,服务退出.它不会为每个意图创建独立的线程.我不知道任何以您描述的方式工作的Service子类,您可能必须编写自己的子类.

  • IntentService的设计模式是一个工作队列,它保证请求排队而不是并行处理.如下所述,您可以为每个并行工作触发AsyncTask.确保您的服务代码是可重入的. (3认同)