Skip to content Skip to sidebar Skip to footer

How To Access 'activity' From A Service Class Via Intent?

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 cla

Solution 1:

You can use bindService(Intent intent, ServiceConnection conn, int flags) instead of startService to initiate the service. And the conn will be a inner class just like:

privateServiceConnection conn = newServiceConnection() {

    @OverridepublicvoidonServiceConnected(ComponentName name, IBinder service) {
        mMyService = ((CommunicationService.MyBinder) service).getService();
    }

    @OverridepublicvoidonServiceDisconnected(ComponentName name) {

    }
};

mMyService is the instance of your CommunicationService.

In your CommunicationService, just override:

public IBinder onBind(Intent intent) {
    returnnewMyBinder();
}

and the following class in your CommunicationService:

publicclassMyBinderextendsBinder {
    public CommunicationService getService() {
        return CommunicationService.this;
    }
}

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:

publicinterfaceOnChangeListener {
    publicvoidonChanged(int progress);
}

and in your service, please add a public method:

publicvoidsetOnChangeListener(OnChangeListener onChangeListener) {
    this.mOnChangeListener = onChangeListener;
}

you can use the onChanged in your service anywhere, and the implement just in your activity:

publicvoidonServiceConnected(ComponentName name, IBinder service) {
        mMyService = ((CommunicationService.MyBinder) service).getService();
        mMyService.setOnChangeListener(newOnChangeListener() {
            @OverridepublicvoidonChanged(int progress) {
                // anything you want to do, for example update the progressBar// mProgressBar.setProgress(progress);
            }
        });
    }

ps: bindService will be like this:

this.bindService(intent, conn, Context.BIND_AUTO_CREATE);

and do not forget

protectedvoidonDestroy() {
    this.unbindService(conn);
    super.onDestroy();
}

Hope it helps.

Post a Comment for "How To Access 'activity' From A Service Class Via Intent?"