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