Settasit7
Settasit7

Reputation: 65

How to kill previous service before start new service in Java?

I am coding an Android app using Android Studio.

My service class takes the values from the main activity class when starting the service.

However, when I reassign the values in the main activity, the change is not applied to the value in the service. Then, I tried to start a new service every time after reassigning the values, but it makes two services run at the same time.

Therefore, I would like to know if is there any way to remove the previous service when I start the new one. I am not sure if onDestroy() can do what I want. As far as I tried, I still can not make it.

This is the service class code:

public class ForegroundService extends Service {

double x1 = MainActivity.x1;
double y1 = MainActivity.y1;
double radius_ = MainActivity.radius_;
int k = MainActivity.k;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new Thread(
            new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        Log.e("Service", "Running " + String.valueOf(x1));
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
    ).start();
    return super.onStartCommand(intent, flags, startId);
}

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

}

After reassign x1, it shows two x1 value every one second:

E/Service: Running 35.6761919

E/Service: Running 35.4436739

Upvotes: -1

Views: 167

Answers (1)

David Wasser
David Wasser

Reputation: 95626

Your Service is never shut down. When you start it the first time from the Activity by calling startService(), the Service instance is created and this will initialize the values of x, y, k, etc. from MainActivity and onStartCommand() is called. You then start a thread that counts and logs. This thread runs forever (until Android kills off the OS process hosting your app). If you now do something in your Activity that changes the values of xc, y, k, etc. and then calls startService() again, this doesn't start another Service instance. Your Service is already running. So it just calls onStartCommand() again. This starts another thread that counts and logs. Now you have 2 threads that are counting and logging.

Also, it is bad practice to have a Service copy values from an Activity like this. It is better to put these values in the Intent you pass to startService() as "extras". You can then access these values in onStartCommand() as the Intent is passed through as a parameter to onStartCommand().

Upvotes: 0

Related Questions