IntentService 串联 按顺序执行(此次任务执行完才执行下一个任务)

IntentService与Service的最大区别就是前者依次执行,执行完当前任务才执行下一个任务,后者并发执行

在IntentService里面不写onCreate方法

MainActivity:

 1 package com.zzw.test1;
 2 
 3 import android.app.Activity;
 4 import android.content.Intent;
 5 import android.os.Bundle;
 6 import android.os.SystemClock;
 7 
 8 public class MainActivity extends Activity {
 9 
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14         int value[] = new int[2];
15         for (int i = 1; i <= 20; i++) {
16             Intent intent = new Intent(this, TestAppIntentService.class);
17             value[0] = i;
18             value[1] = 20 - i;
19             intent.putExtra(Contants.KEY, value);
20             startService(intent);
21         }
22     }
23 
24     @Override
25     protected void onDestroy() {
26         super.onDestroy();
27         Intent intent = new Intent(this, TestAppIntentService.class);
28         stopService(intent);
29     }
30 
31 }

TestAppIntentService:

 1 package com.zzw.test1;
 2 
 3 import android.app.IntentService;
 4 import android.content.Intent;
 5 import android.util.Log;
 6 import android.widget.Toast;
 7 
 8 public class TestAppIntentService extends IntentService {
 9     int count = 1;
10 
11     // 只能写空的构造方法
12     public TestAppIntentService() {
13         super("TestAppIntentService");
14         // TODO Auto-generated constructor stub
15     }
16 
17     // 相当于一个线程 不用在里面另外new一个线程
18     @Override
19     protected void onHandleIntent(Intent intent) {
20         Log.d("------", count + "-------开始");
21         int[] value = intent.getIntArrayExtra(Contants.KEY);
22         int sum = value[0] * value[1];
23         Log.d("-------------", value[0] + "*" + value[1] + "=" + sum);
24         Log.d("------", count + "-------结束");
25         count++;
26     }
27 
28 }

 

posted on 2015-11-09 10:36  Z2  阅读(769)  评论(0编辑  收藏  举报

导航