服务的基本用法java
定义服务: 咱们须要先建立服务,咱们要使用就的利用一个类去继承它,而后重写它的几个方法,具体的咱们看下面的代码:多线程
咱们重写了下面三个方法:ide
* onCreate() 服务建立的时候调用this
* onStartCommand() 每次服务启动的时候调用线程
* onDestory() 服务销毁的时候调用3d
注意点: 首先要明白咱们的onCreate()方法,咱们说了它只会在服务被建立的时候调用,以后你开启服务的时候是不会再调用这个onCreate()方法了,没启动一次只会走 onStartCommand()方法,onDestory()是在服务被销毁的时候调用,下面咱们再看看它的启动。component
Intent startIntent = new Intent(this,MyService.class); // 启动服务 startService(startIntent); // 中止服务 stopService(startIntent);
活动和服务之间的通讯blog
首先咱们的完善咱们的服务类,在咱们的服务类中添加 Binder 类,这个类会对咱们想要在服务类中作的事作一个管理:继承
class MyService extends Service{ public MyService() { } private DownloadBinder downloadBinder = new DownloadBinder(); class DownloadBinder extends Binder{ public void startDownload(){ Log.d("DownloadBinder","startDownload"); } public int getProgress(){ Log.d("DownloadBinder","getProgress"); return 0; } } @Nullable @Override public IBinder onBind(Intent intent) { return downloadBinder; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); } }
接着咱们看在活动里面是怎样和这个服务类进行一个绑定的,具体的须要注意的地方咱们都加了注释,就不在这里在重复,注意看注释就能够:生命周期
/* * * 首先咱们建立一个ServiceConnection匿名类,在里面重写了onServiceConnected和onServiceDisconnected方法 * 这两个方法分别在活动和服务成功绑定的时候和解绑的时候调用 * * */ private MyService.DownloadBinder downloadBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { // 绑定成以后咱们就能够随意的使用调用服务中的方法了 downloadBinder = (MyService.DownloadBinder) iBinder; downloadBinder.startDownload(); downloadBinder.getProgress(); } @Override public void onServiceDisconnected(ComponentName componentName) { } }; // 绑定和解绑按钮事件来绑定和解绑 @Override public void onClick(View view) { switch (view.getId()){ // 活动绑定服务 case R.id.bind_service: // 绑定的时候使用bindService方法,参数分别是 Intent 和 connection Intent bindIntent = new Intent(this,MyService.class); bindService(bindIntent,connection,BIND_AUTO_CREATE); break; // 活动解绑服务 case R.id.unbind_service: unbindService(connection); break; default: break; } }
服务的生命周期
咱们经过下面的两张图说一下服务的生命周期:
Service生命周期流程图:
咱们在经过下面的一个调用顺序来解读一下这生命周期:
服务使用的两个小技巧
可咱们还有更简单的方法来作这件事,利用咱们要说的 IntentService