1.Service不是一个单独的进程 ,它和应用程序在同一个进程中。
2.Service不是一个线程,所以我们应该避免在Service里面进行耗时的操作.
IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。
例子
1.定义普通Service
/**
* 普通的Service
*
*
@author
Administrator
*
*/
public
class
MyService
extends
Service {
@Override
public
IBinder onBind(Intent intent) {
return
null
;
}
@Override
public
int
onStartCommand(Intent intent,
int
flags,
int
startId) {
System.
out
.println(
"开始睡!"
);
SystemClock. sleep(20000);
System.
out
.println(
"停止睡"
);
return
super
.onStartCommand(intent, flags, startId);
}
}
2.定义IntentService
/**
* IntentService
*
*
@author
Administrator
*
*/
public
class
MyIntentService
extends
IntentService {
// IntentService必须提供一个无参的构造,不然会发生异常
public
MyIntentService() {
super
(
"testIntentService"
);
}
@Override
protected
void
onHandleIntent(Intent intent) {
System.
out
.println(
"开始睡!"
);
SystemClock. sleep(20000);
System.
out
.println(
"停止睡"
);
}
}
3.定义测试类:
public
class
MainActivity
extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
}
// IntentService
public
void
intentService(View view) {
Intent intentService =
new
Intent(
this
, MyIntentService.
class
);
startService(intentService);
}
// 普通Service
public
void
Service(View view) {
Intent service =
new
Intent(
this
, MyService.
class
);
Intent service1 =
new
Intent(
this
, MyService.
class
);
Intent service2 =
new
Intent(
this
, MyService.
class
);
startService(service);
startService(service1);
startService(service2);
}
}