jenil
jenil

Reputation: 141

Not able to run service indefinitley in background

I am working on below code to run a service in background,but the problem is i am not getting how to run the service indefinitely even though the app is closed,here on press of back my service is stopping.I have read many tutorials but still confused with this.

public class HelloService extends Service {
    private static final String TAG = "HelloService";
    private boolean isRunning = false;
    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate");
        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Service onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                    if (isRunning) {
                        Log.i(TAG, "Service running");
                    }
                }
                //Stop service once it finishes its task
                stopSelf();
            }
        }).start();

        return Service.START_STICKY;
    }
    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "Service onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        isRunning = false;
        Log.i(TAG, "Service onDestroy");
    }
}

Upvotes: 0

Views: 45

Answers (2)

user2248671
user2248671

Reputation: 52

One Way is to use while loop but keep a check i.e

while(true) {
    if (condition != true) {
        Thread.sleep(time);
    } else {
        break;
    }
}

Upvotes: -1

greywolf82
greywolf82

Reputation: 22193

On Android there is NO way (at least for a third party app) to have a never ending process running. The system can always kill your service. So you can use a foreground service but the system can kill your service even in this case (even with low probability). In addition, you should consider that the cpu can go to sleep. So you should take a wakelock but in this way you can kill the user battery so it's not a good solution. My suggestion is to always work "on event" for example with a brodacast receiver that starts a intent service, it does some work and then exit. The always running processes are simply a wrong design choices on Android.

Upvotes: 2

Related Questions