简体   繁体   中英

Android library project: calling a method of an inner class

I'm in the process of splitting an Android project into a library project + several dependent projects, and ran into this problem.

The library project has an Android Service defined like this:

public class UserService extends Service {

    public class LocalBinder extends Binder {
        UserService getService() {
            return UserService.this;
        }
    }
    ...
}

The dependent project makes a call to a method of an inner class of the Service like this:

public ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;            
    }
    ...
};

This works fine when everything's in the same project. But after I moved the Service into the library project, it gives a compile-time error:

The method getService() from the type UserService.LocalBinder is not visible

What do I need to change to make it compile?

Your method doesn't have any visibility modifier, so it's only visible from classes in the same package. Make it public to make it accessible from any other class:

    public UserService getService() {
        return UserService.this;
    }

Read the Java tutorial to learn about visibility modifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM