janishar / android-mvp-interactor-architecture

Extension of the android-mvp-architecture for very large projects.
Apache License 2.0
405 stars 97 forks source link

JobService using getApplication() for daggerServiceComponent causing a Class cast exception. #10

Open aomari opened 6 years ago

aomari commented 6 years ago

I have an exception "Class Cast Exception" that is happening on Android 7.0 when try to use the getApplication() inside the service

ServiceComponent component = DaggerServiceComponent.builder() .applicationComponent(((MediCountApplication) getApplication()).getComponent()) .build(); component.inject(this);

Exception is: java.lang.RuntimeException: at android.app.ActivityThread.handleCreateService (ActivityThread.java:3544) at android.app.ActivityThread.-wrap6 (ActivityThread.java) at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1732) at android.os.Handler.dispatchMessage (Handler.java:102) at android.os.Looper.loop (Looper.java:154) at android.app.ActivityThread.main (ActivityThread.java:6776) at java.lang.reflect.Method.invoke (Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1496) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1386) Caused by: java.lang.ClassCastException: at global.medicount.healthpass.services.NetworkSchedulerService.onCreate (Unknown Source) at android.app.ActivityThread.handleCreateService (ActivityThread.java:3534)

Service Java Class

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
 public class NetworkSchedulerService extends JobService {
    @Inject
    NetworkStateChangeReceiver mConnectivityReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        ServiceComponent component = DaggerServiceComponent.builder()
                .applicationComponent(((MediCountApplication) getApplication()).getComponent())
                .build();
        component.inject(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        registerReceiver(mConnectivityReceiver, new IntentFilter(AppConstants.CONNECTIVITY_ACTION));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        try {
            unregisterReceiver(mConnectivityReceiver);
        } catch (IllegalArgumentException e) { }
        return true;
    }
}

After google it I have found the following reference here. And unfortunately, there's no real fix to this rare crash. Google won't fix the lifecycle-related issue, but said it reduced in Android 7.1+.

Is there any way to fix this issue when we use this MVP structure ?