我在一个程序包(packageShared)中有一个GpsService,我需要从另一个程序包(packageClient)中访问它。我收到“ getService()在'packageShared.GpsService.Localbinder'中不公开。无法从外部程序包访问。”在以下行mService =(GpsService)binder.getService();在Android Studio中。
包装内还有另一个类。使用相同的代码可以很好地共享作品。
这是packageClient上的代码:
// Monitors the state of the connection to the service.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
GpsService.LocalBinder binder = (GpsService.LocalBinder) service;
mService = (GpsService) binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBound = false;
}
};
这是共享包上的代码:
public class GpsService extends Service {
public GpsService() {
}
other methods here...
/**
* Class used for the client Binder. Since this service runs in the same process as its
* clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
GpsService getService() {
return GpsService.this;
}
}
}
谢谢。
答案 0 :(得分:1)
这是因为您的getService()
方法是程序包可见的。您需要使其public
才能从其他软件包中访问它:
public class LocalBinder extends Binder {
public GpsService getService() { //<-- The public keyword is added
return GpsService.this;
}
}