I have Application that contains main Activity, Service and several Threads run on this Service. The Activity has 1 button ‘Start service‘ and other UI. When user press on button, the name of button changes to ‘Stop service‘, the program creates new Service that stores information about CPU usage and pastes stored information to TextVeiw with frequency every 1 second.
Lets say I stopped main Activity. The Service continues to run but there is no any Activity that Service can pass data over.
After 1 min. I launch main Activity again. First of all I want to see above mentioned button state (name) ‘Stop service‘ and I want to see the old service which continue to talk with my new Activity.
I don’t intend to use LocalBinder and bindService(...); method since my Service stays in my own Application.
Any solutions?
Here is an extensive code example.
On start, Activity renders the instance to Application. Our Application will store instance of main Activity (or in other words Interface of Activity)
see
GuiServiceBridgeItf gsbsnippets Application class
GuiServiceBridgeItf interface
Here is our Service that implements the same Interface
GuiServiceBridgeItf.MyServiceruns 2 Threads:One Thread runs some logic (in our case notify Activity on CPU every second)
Second one notifies main Activity if Service runs (maybe better to provide this task to Activity to ask if Service runs)
The main method here is:
boolean isInstanceActive()that returnstrueorfalseonActivity state. In other words if we down Activity, we unregister it’s instance from Application. Because
onDestroymethod in main Activity resetsMyApplication.gsb.In other hand when we relaunch new Activity, we register it to Application again, (see below)
the Service, by using his Thread, validates that Activity registered to Application and therefore continues to notify newborn Activity about CPU change. For now Activity can update button name to ‘Stop service‘ and do other stuff