服务Service
继承Service类,重新常用方法:
onCreate(),
onDestroy(),
onStartCommand();
onBind();
Service的逻辑完成后,需要在AndroidManifest.xml中注册申明:
<service
android:name="com.example.sevenchapter.MyService"></service>
使用startService()启动服务;
使用stopService()停止服务;
活动和服务进行通信:
bindService()
unBindService()
这两个方法接收ServiceConnection的实例对象作为参数。
ServiceConnection需要实现两个方法:
onServiceConnected()和 onServiceDisconnected()
这两个方法分别会在活动与服务成功绑定以及解除绑定的时候调用
public class MainActivity extends Activity implements OnClickListener {
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.getDownload();
}
};
......
}
Service的代码:
public class MyService extends Service {
private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void getDownload() {
// TODO 自动生成的方法存根
Log.d("MyService", "get donwload progress");
}
public void stopDownload() {
// TODO 自动生成的方法存根
Log.d("MyService", "stop donwload progress");
}
}
public IBinder onBind(Intent intent) {
// TODO 自动生成的方法存根
return mBinder;
}
.....
}
在 MyService中创建了 DownloadBinder的实例,然后在 onBind()方法里返回了这个实例。
在 onServiceConnected()方法中,我们又通过向下转型得到了 DownloadBinder的实例,就可以调用里面的public公共方法。