I am new to Android programming - so I do not have very clear understanding of the 'Context' and the 'Intent'.
I want to know is there a way to access Activity from a Service class?
i.e. Let's say I have 2 classes - one extends from "Activity" and other extends from "Service" and I have created an intent in my Activity class to initiate the service.
Or, how to access the 'Service' class instance from my 'Activity' class - because in such workflow Service class is not directly instantiated by my Activity-code.
public class MainActivity extends Activity {
.
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, CommunicationService.class));
.
.
}
public class CommunicationService extends Service implements ..... {
.
.
@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
super.onStartCommand(intent, flags, startId);
....
}
}
You can use
bindService(Intent intent, ServiceConnection conn, int flags)
instead ofstartService
to initiate the service. And theconn
will be a inner class just like:mMyService
is the instance of yourCommunicationService
.In your
CommunicationService
, just override:and the following class in your
CommunicationService
:So you can use
mMyService
to access any public methods and fields in your activity.In addition, you can use callback interface to access activity in your service.
First write a interface like:
and in your service, please add a public method:
you can use the
onChanged
in your service anywhere, and the implement just in your activity:ps:
bindService
will be like this:this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
and do not forget
Hope it helps.