我有这样的服务:
public MyService extends Service {
// ...
IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
// ...
}
在Activity中我收到Binder从而得到Service实例,之后我可以访问它的所有方法。我想知道,那样做是否安全?或者我应该只通过Binder界面与服务进行交互?谢谢!
答案 0 :(得分:2)
在Activity中我收到Binder从而得到Service实例,之后 我可以访问它的所有方法。我想知道,是否安全 那样的吗?或者我应该只通过Binder与服务进行交互 接口
Binder是返回的内容,您只需转换为您知道的Service类。你正在做的方式只是使用Binder ......
你完成它的方式通常是如何完成的。这是直接从这里找到的“官方”样本中获取的“本地服务”模式:http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html在您的Service类上调用方法的其他方法非常hacky(相信我,我之前已经尝试过)。
示例:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
myService = ((MyService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
}
};