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
Your
Serviceis never shut down. When you start it the first time from theActivityby callingstartService(), theServiceinstance is created and this will initialize the values ofx, y, k, etc.fromMainActivityandonStartCommand()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 yourActivitythat changes the values ofxc, y, k, etc.and then callsstartService()again, this doesn't start anotherServiceinstance. YourServiceis already running. So it just callsonStartCommand()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
Servicecopy values from anActivitylike this. It is better to put these values in theIntentyou pass tostartService()as "extras". You can then access these values inonStartCommand()as theIntentis passed through as a parameter toonStartCommand().