inner class: not public 并且不能从外部包访问

inner class: not public and cannot be accessed from outside package

我在一个包 (packageShared) 中有一个 GpsService,我需要从另一个包 (packageClient) 访问它。我在以下行中得到 "getService() is not public in 'packageShared.GpsService.Localbinder'. Can not be accessed from outside package." mService = (GpsService) binder.getService();在 Android 工作室。

我还有一个 class 在包里用相同的代码分享了很棒的作品。

这里是 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;
    }
};

这是 packageShared 上的代码:

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;
        }
    }
}

提前致谢。

因为你的getService()方法是package-visible。您需要将其设置为 public 以便从其他包访问它:

public class LocalBinder extends Binder {
    public GpsService getService() {   //<-- The public keyword is added
        return GpsService.this;
    }
}