ning
ning

Reputation: 2131

How can I reference a boolean variable from an intent (background service)?

I have a background service GpxService:

public class GpxService extends Service implements LocationListener {
    public boolean is_recording;
    ...
}

I am able to start this service as a background service in my MainActivity:

gpxService = new Intent(MainActivity.this, GpxService.class);
gpxService.setAction(GpxService.START_SERVICE);
// notification, startForeground, etc. managed within gpxService onStartCommand
startService(gpxService);

How can I access the flag boolean is_recording in the Intent gpxService in the MainActivity?


Background: I have two buttons, record and stop. In the onCreate method of MainActivity, I use setEnabled to grey out one and leave the other clickable. I want which button is greyed and which is left clickable to depend on the boolean flag is_recording in the background service.

I can't have is_recording in MainActivity since it is sometimes destroyed to clear memory. In this case, with the background service still running, reopening the app will reset the is_recording flag, triggering the if statement wrongly, and greying out the wrong button.

Upvotes: 0

Views: 78

Answers (3)

nstosic
nstosic

Reputation: 2614

For cases such as yours, you should be using IBinder to establish a connection between the Service object and your Activity instance.

Take a look at the bindService call and after establishing the connection you'll be able to access all the public fields and methods of your active GpxService instance.

Upvotes: 1

user7774943
user7774943

Reputation:

another idea: try making that service a subclass of mainActivity, tho it dosent sound as a proper way of doing it

Upvotes: 0

user7425922
user7425922

Reputation:

Try to solve it by creating an object and access the variables inside the class.... it may work

Upvotes: 0

Related Questions