I have an activity in which I start a service, for example I staty MyService as:
Intent intent1 = new Intent(this, MyService.class);
startService(intent1);
Inside my service I create a thread and run it. Here is part of my code:
public class MyService extends Service {
...
@Override
public void onStart(Intent intent, int startid) {
Thread mythread= new Thread() {
@Override
public void run() {
while(true)
{
...
}
}
};
mythread.start();
}
}
Now instead of while(true) I want to use while(a), where a is a parameter that is passed from my activity to this service. Please note that my activity is a different class than my service. How can this be done? Please show specific example with some codes.
You can get access to your service by binding to it. Edit your service class so that it returns an IBinder onBind()
Now in your activity you need to handle binding and unbinding to your service. In this example, the service sticks around whether you are bound or not. If this is not the functionality you want, you can just not call
startService(...):Now you have a reference to your bound service in your activity and you can just call
myService.setA(true)to set your parameter.