【问题标题】:inner class: not public and cannot be accessed from outside package内部类:不公开,不能从外部包访问
【发布时间】:2020-07-07 00:42:08
【问题描述】:

我在一个包 (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;
    }
};

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

提前谢谢你。

【问题讨论】:

    标签: android package inner-classes public


    【解决方案1】:

    这是因为您的 getService() 方法是包可见的。您需要将其设为 public 才能从其他包中访问它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      相关资源
      最近更新 更多