Android Service Needs to Run Always (Never Pause or Stop)

Android service required to run constantly in evey ten minutes

Android OS will notify when you install application form play store.

1. Add receiver in manifest file, which will notify you that user has installed application:

<receiver android:name="com.mypackagename.Installreceiver" android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>

2. Start service which will run continues every 10 minutes from Installreceiver broadcast receiver.

public class Installreceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), YourService.class));
}
}

YourService.java:

public class YourService extends Service {

private static String TAG = "MyService";
private Handler handler;
private Runnable runnable;
private final int runTime = 10000;

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");

handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {

handler.postDelayed(runnable, runTime);
}
};
handler.post(runnable);
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onDestroy() {
super.onDestroy();
}

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

Update 1:

3. If OS kill your service then you need to start again by doing another receiver.

Add below two methods in service:

@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("IWillStartAuto"));
}

@Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("IWillStartAuto"));
}

4. Add receiver in manifest.

<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="IWillStartAuto" >
</action>
</intent-filter>
</receiver>

5. Add receiver:

public class RestartServiceReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), YourService.class));
}
}

Update 2:

6. Add permission in manifest.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

7. Add receiver in manifest.

<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>

7. BootCompletedReceiver,java:

public class BootCompletedReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent arg1) {
context.startService(new Intent(context.getApplicationContext(), YourService.class));
}
}

Hope this will help you.

Continually Running Background Service

In oreo release Android defined limits to background services.

To improve the user experience, Android 8.0 (API level 26) imposes
limitations on what apps can do while running in the background.

Still if app need to run its service always, then we can create foreground service.

Background Service Limitations: While an app is idle, there are limits
to its use of background services. This does not apply to foreground
services, which are more noticeable to the user.

So create a foreground service. In which you will put a notification for user while your service is running. See this answer (There are many others)

Now what if you don't want a notification for your service. A solution is for that.

You can create some periodic task that will start your service, service will do its work and stops itself. By this your app will not be considered battery draining.

You can create periodic task with Alarm Manager, Job Scheduler, Evernote-Jobs or Work Manager.

  • Instead of telling pros & cons of each one. I just tell you best. Work manager is best solution for periodic tasks. Which was introduced with Android Architecture Component.
  • Unlike Job-Scheduler(only >21 API) it will work for all versions.
  • Also it starts work after a Doze-Standby mode.
  • Make a Android Boot Receiver for scheduling service after device boot.

I created forever running service with Work-Manager, that is working perfectly.

Foreground Service dont run constantly

There is not a single... Many problems in your code... You may be getting it "0 Errors" as it is syntactically correct but it is androidicaly wrong, your basics are poor, reading of android documentation and implementation is very poor. Android never runs very poor things...

Problem : 1

Do you know for a service conventionally you should override onCreate, onStartCommand, onBind, onDestroy methods....?

I don't see onDestroy there....!!

Problem : 2

Do you know how to notify...? Your onStartCommand implementation is again making no sense.

KEEP IT EMPTY JUST RETURN START_STICKY

Problem : 3

How do you expect to run this under background execution limits...? Notify android first by making notification in oncreate only and with startforeground if needed...

I don't see it there.... you trying to do it in onstartcommand and again it is very poorly...

Well... take a look at working code below :

public class RunnerService extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";

public RunnerService() { }

@Override
public void onCreate()
{
super.onCreate();

Log.d("RUNNER : ", "OnCreate... \n");

Bitmap IconLg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);

mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("My App")
.setContentText("Always running...")
.setTicker("Always running...")
.setSmallIcon(R.drawable.ic_menu_slideshow)
.setLargeIcon(IconLg)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(new long[] {1000})
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true)
.setAutoCancel(false);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotifyManager.createNotificationChannel(notificationChannel);

mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
else
{
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyManager.notify(1, mBuilder.build());
}
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d("RUNNER : ", "\nPERFORMING....");

return START_STICKY;
}

@Override
public void onDestroy()
{
Log.d("RUNNER : ", "\nDestroyed....");
Log.d("RUNNER : ", "\nWill be created again automaticcaly....");
super.onDestroy();
}

@Override
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("NOT_YET_IMPLEMENTED");
}
}

How to check....???

Remove the app from recents list and you should see in your logs the "Performing " message in logcat...

In what conditions it stops...?

It never stops ( until next boot..!! )... Yes it stops when user force stops application. And rarely if system finds it is having very low resources .... which is a very rare condition seems to occur as android has improved a lot over the time....

How to start it....?????

Wherever it may be from mainactivity or from receiver or from any class :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
context.startForegroundService(new Intent(context, RunnerService.class));

}
else
{
context.startService(new Intent(context, RunnerService.class));

}

How to check is service started or not....?

Simply Don't..... Even if you starts service how many times you wants.... If it is already running... then it won't be start again.... If not running then... will start it...!!



Related Topics



Leave a reply



Submit