Java.lang.NoSuchMethodError: no virtual getSystemService method
I am trying to implement a jobcheduler to call a jobservice that starts every 5 minutes to collect the time taken for a specific geolocation. but the code below works for Marshmallow and above, but its crash for lollipop and below. this is my code ->
ComponentName serviceComponent = new ComponentName(context, SyncDbToServerJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
PersistableBundle bundle = new PersistableBundle();
bundle.putString(Constants.ENTERED_TIME, enteredTime);
builder.setPeriodic(intervalMillis).setExtras(bundle).setPersisted(true);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
builder.setRequiresDeviceIdle(true); // device should be idle
builder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
this is how to make a mistake →
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
this is my log error ->
04-19 11:38:25.358 1986-4658/com.eonelectric.eon E/AndroidRuntime: FATAL EXCEPTION: IntentService[GeofenceTransitionsIS]
Process: com.eonelectric.eon, PID: 1986
java.lang.NoSuchMethodError: No virtual method getSystemService(Ljava/lang/Class;)Ljava/lang/Object; in class Landroid/content/Context; or its super classes (declaration of 'android.content.Context' appears in /system/framework/framework.jar)
at com.eonelectric.eon.GeneralUtil.startSyncAlarm(GeneralUtil.java:440)
at com.eonelectric.eon.beatTrack.GeofenceTransitionsIntentService.getGeofenceTransitionDetails(GeofenceTransitionsIntentService.java:137)
at com.eonelectric.eon.beatTrack.GeofenceTransitionsIntentService.onHandleIntent(GeofenceTransitionsIntentService.java:96)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
source to share
Try this it will work for lolipop
ComponentName jobService =
new ComponentName(getApplicationContext().getPackageName(), SyncService.class.getName());
JobInfo.Builder builder = new JobInfo.Builder(0, jobService);
builder.setPeriodic(10000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
jobScheduler = (JobScheduler) this.getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
source to share
If your app is targeting Android 5.0 (API level 21) or higher, Google recommends using JobScheduler to perform background tasks.
But in API level 23 was added getSystemService (serviceClass)
.
So use
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE)
also include API 21 and 22
source to share