javaandroidandroid-studioandroid-studio-3.1

Can Application class be package-private?


My Application class code:

import android.app.Application;
import android.os.Process;

import com.squareup.leakcanary.LeakCanary;

public class SampleApplication extends Application {

    public SampleApplication() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //noinspection ConstantConditions
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        // Normal app init code...
    }

    @Override
    public void onTerminate() {
        System.exit(0);
        Process.killProcess(Process.myPid());

        super.onTerminate();
    }
}

Android Studio 3.1 Canary 7 --> Analyze --> Inspect Code --> OK:

Declaration access can be weaker inspection

1 warning: SampleApplication can be package-private

Can Application class be package-private or it's lint error?


Solution

  • Yes it can be package private. Check out this question in Stack overflow and also read this to learn how to control access to members of a class.

    For a further explanation: inhering from Application alows you to start the app without a main method (the class which inherits acts as the main class). It needs to be public if you're accessing other packages with it. If not, you can set it as package-private.