1.创建启动形式Service
public class HelloService extends Serivce{
@Override
public void onCreate(){
super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flag,int startId){
return super.onStartCommand(intent,flags,startId);
}
@Override
public IBinder onBind(Intent intent){
return null;
}
@Override
public void onDestroy(){
super.onDestroy();
}
}
onCreate:Service 在创建时被调用
onStartCommand:Serivice启动后会回调这方法
onBind:绑定服务,由于是启动形式Service,所以这里返回的null
onDestroy:Service在销毁时调用
注意点:不推荐在创建Service是直接继承Service类。
因为Service是远行在主线程中的,它不会创建一个新的线程,这也就意味着,Service中不适合执行任何耗时的操作,因为一旦你执行耗时的操作主线程就会卡死应用就会进入假死状态
Android系统还提供了另外一个Service的拓展类:IntentService
IntentService类会使用队列的形式将请求的Intent加入队列,然后开启一个默认的线程来处理请求,如果连续启动IntentService应用程序也不会阻塞,因为它会在处理完上一个请求之后处理下一个请求(IntentService采用单独的线程)。
public class HelloIntentService extends IntentService{
public HelloIntentService(){
super("HelloIntentService");
}
@Override
protected void onHandleIntent(Intent intent){
}
}