Service-(服务)初视
Service是什么
Service是安卓四大组件之一,不需要有任何用户界面,能一直保持正常运行,因此它能够实现后台长期运行的一些任务,是Android中实现程序后台运行的解决方案。
服务并不是运行在一个独立的进程当中的,它也依赖创建服务时所在的应用程序进程。进程被杀掉时,所有依赖于该进程的服务会停止。
Android中使用Service的方式有两种:
StartService()启动Service
BindService()启动Service
相关方法
onCreate():当Service第一次被创建后立即回调该方法,该方法在整个生命周期中只会调用一次
onDestory():当Service被关闭时会回调该方法,该方法只会回调一次
onStartCommand(intent,flag,startId):早期版本是onStart(intent,startId), 当客户端调用startService(Intent)方法时会回调,可多次调用StartService方法, 但不会再创建新的Service对象,而是继续复用前面产生的Service对象,但会继续回调 onStartCommand()方法
IBinder onOnbind(intent):该方法是Service都必须实现的方法,该方法会返回一个 IBinder对象,app通过该对象与Service组件进行通信
onUnbind(intent):当该Service上绑定的所有客户端都断开时会回调该方法
IntentService的用法
public class TestService3 extends IntentService { private final String TAG = "hehe"; //必须实现父类的构造方法 public TestService3() { super("TestService3"); } //必须重写的核心方法 @Override protected void onHandleIntent(Intent intent) { //Intent是从Activity发过来的,携带识别参数,根据参数不同执行不同的任务 String action = intent.getExtras().getString("param"); if(action.equals("s1"))Log.i(TAG,"启动service1"); else if(action.equals("s2"))Log.i(TAG,"启动service2"); else if(action.equals("s3"))Log.i(TAG,"启动service3"); //让服务休眠2秒 try{ Thread.sleep(2000); }catch(InterruptedException e){e.printStackTrace();} } //重写其他方法,用于查看方法的调用顺序 @Override public IBinder onBind(Intent intent) { Log.i(TAG,"onBind"); return super.onBind(intent); } @Override public void onCreate() { Log.i(TAG,"onCreate"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG,"onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void setIntentRedelivery(boolean enabled) { super.setIntentRedelivery(enabled); Log.i(TAG,"setIntentRedelivery"); } @Override public void onDestroy() { Log.i(TAG,"onDestroy"); super.onDestroy(); } }
部分内容参考自菜鸟教程