START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also … Read more

Trying to start a service on boot on Android

The other answers look good, but I thought I’d wrap everything up into one complete answer. You need the following in your AndroidManifest.xml file: In your <manifest> element: <uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” /> In your <application> element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver): <receiver android:name=”com.example.MyBroadcastReceiver”> <intent-filter> <action android:name=”android.intent.action.BOOT_COMPLETED” /> </intent-filter> … Read more

getApplication() vs. getApplicationContext()

Very interesting question. I think it’s mainly a semantic meaning, and may also be due to historical reasons. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want … Read more

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, ServedService.class)); } else { context.startService(new Intent(context, ServedService.class)); } And in service class, please add the code below for notification: … Read more

Service vs IntentService in the Android platform

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService. When to use? The Service can be used in tasks with no UI, but shouldn’t be too long. If you need to perform long tasks, you must use threads within Service. The IntentService can be used in … Read more

How to check if a service is running on Android?

I use the following from inside an activity: private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } And I call it using: isMyServiceRunning(MyService.class) This works reliably, because it is based on the information about running services provided by … Read more