Java – Why can’t I declare an intent service as a private package?

Why can’t I declare an intent service as a private package?… here is a solution to the problem.

Why can’t I declare an intent service as a private package?

I’m working on an Android library, so I want to keep all library code packages private, except for a few classes that library users need access to.

In these classes there is an IntentService. However, the application crashes with this error:

java.lang.RuntimeException: Unable to instantiate service com.library.sdk.SaveDataIntentService: java.lang.IllegalAccessException: java.lang.Class< com.library.sdk.SaveDataIntentService> is not accessible from java.lang.Class<android.app.ActivityThread>
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3304)
    at android.app.ActivityThread.-wrap5(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6349)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)

Caused by: java.lang.IllegalAccessException: java.lang.Class<com.library.sdk.SaveDataIntentService> is not accessible from java.lang.Class<android.app.ActivityThread >
    at java.lang.Class.newInstance(Native Method)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3301)
    at android.app.ActivityThread.-wrap5(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6349) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783) 

Even list displays a warning because the intent service is not declared as public.

What exactly is causing this, and why do you need to expose the intent service?

Solution

What exactly is causing this

Java classes outside the package need to create an instance of IntentService.

why does the intent service need to be public?

Because Java classes outside the package cannot create instances of the private class of the package, nor can they call the private constructor.

Related Problems and Solutions