问题:
当程序通过startService()和stopService()启动、关闭Service时Service与访问者不存在太多关联,因此service与用户之间无法进行通信、交换数据。
解决:
如果Service 和访问者之间需要进行方法调用或数据交互,则应使用 bindService()和unbindService() 方法启动、关闭Service。
BindService使用:
使用效果:(主活动中获得Service的count数据)
BindService的定义:
代码语言:javascript复制public class BindService extends Service {
private int count;
private boolean quit;
//定义onBinder 方法所返回的对象
private MyBinder binder = new MyBinder();
//实现MyBinder
public class MyBinder extends Binder{
public int getCount(){
//获取count
return count;
}
}
public BindService() {
}
//绑定改Service时回调该方法
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.v("myService","Service is Binder");
return binder;
}
//Service被创建时回调该方法
@Override
public void onCreate() {
super.onCreate();
Log.v("myService","service is created");
//启动一个线程动态的修改 count 值;
new Thread(){
@Override
public void run() {
while (!quit){
try{
Thread.sleep(1000);
}catch (Exception e){
}
count ;
}
}
}.start();
}
//Service 断开连接时回调该方法
@Override
public boolean onUnbind(Intent intent) {
Log.v("myService","Service is UnBind");
return true;
}
//Service 关闭之前回调该方法
@Override
public void onDestroy() {
super.onDestroy();
this.quit = true;
Log.v("myService","Service is Destroyed");
}
}
在主活动中启动BindService,并获得service数据:
代码语言:javascript复制public class MainActivity extends AppCompatActivity {
private Button bind,ubind,getServiceStatus;
//创建myBinder对象
private BindService.MyBinder binder;
//定义一个ServiceConnection对象
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.v("myService","--Service Connected--");
//获取Service 的onBind方法所返回的对象MyBinder 对象
binder = (BindService.MyBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.v("myService","--Service Disconnected--");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定 bind,ubind,getServiceStatus按钮
bind = (Button) findViewById(R.id.bind);
ubind = (Button) findViewById(R.id.unbind);
getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
//启动Service 的 Intent
final Intent intent = new Intent(this,BindService.class);
bind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//绑定制定的Service
bindService(intent,conn,Service.BIND_AUTO_CREATE);
}
});
ubind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//解除绑定Service
unbindService(conn);
}
});
getServiceStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取Service 的count
Toast.makeText(MainActivity.this,"Service的 count值为:" binder.getCount(),Toast.LENGTH_SHORT).show();
}
});
}
}
【如果我的介绍对你有帮助,欢迎关注我获得更多资讯】