Skip to content Skip to sidebar Skip to footer

Foreground Service Dont Run Constantly

In my app I use a foreground service that must run constantly. Sometimes the foreground service is stopped. Under what circumstances can the OS kill my service (it happen even if t

Solution 1:

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 overrideonCreate, 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 :

publicclassRunnerServiceextendsService
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
StringNOTIFICATION_CHANNEL_ID="1";

publicRunnerService() { }

@OverridepublicvoidonCreate()
{
    super.onCreate();

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

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

    mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    mBuilder = newNotificationCompat.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(newlong[] {1000})
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setOngoing(true)
            .setAutoCancel(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        notificationChannel = newNotificationChannel(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(newlong[]{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());
    }
}

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

    return START_STICKY;
}

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


@Overridepublic IBinder onBind(Intent intent)
{
    // TODO: Return the communication channel to the service.thrownewUnsupportedOperationException("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(newIntent(context, RunnerService.class));

        }
        else
        {
            context.startService(newIntent(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...!!

Solution 2:

The criticism made in the chosen answer is not reasonable if the service needs an intent to work.

On higher version of Android, System will pause any foreground service while the device is locked, to minimize the power consumption even if it returns START_STICKY. So, to make a foreground task constantly, a wakelock is required.

Here's what android documentation describes wakeLock:

To avoid draining the battery, an Android device that is left idle quickly falls asleep. However, there are times when an application needs to wake up the screen or the CPU and keep it awake to complete some work.

To make a foreground service running constantly, acquire a wakeLock from inside the onCreate().

PowerManagerpowerManager= (PowerManager) getSystemService(POWER_SERVICE);
WakeLockwakeLock= powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyApp::MyWakelockTag");
wakeLock.acquire();

For further detail, have a look at official Android Documentation.

Post a Comment for "Foreground Service Dont Run Constantly"