版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dream_follower/article/details/82915714
创建服务时会自动继承Service类,Service类中有一个onBind()方法,这是唯一一个抽象的方法,然后我们一般需要重写onCreate()、onStartCommand()、onDestory()方法,其中onCreate()只在创建服务的时候才会调用,这一点和onStartCommand()是有区别的,onDestory()在销毁服务的时候调用,onStartCommand()在每次启动服务的时候都会调用。
public class MyService extends Service {
private static final String TAG = "MyService";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"On create");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"Ondestory");
}
}
活动和服务进行通信
如果想要服务和活动进行通信,就需要借助onBind()方法,我们需要创建一个Binder类的子类:
class DownloadBinder extends Binder {
public void startDownload() {
Log.d(TAG,"StartDownload executed");
}
public int getProgress() {
Log.d(TAG,"getProgress executed");
return 0;
}
}
然后就是绑定服务,这里首先需要通过ServiceConnection子类来实现,这里我创建了一个匿名类在MainACtivity类中,并在里面重写了onServiceConnected()和onServiceDisconnected()方法。
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder=(MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
然后就是调用bindService()方法,该方法需要3个参数,第一个是Intent对象,第二个是ServiceConnection的实例,第三个参数是一个标志位。