• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Accessing a Service ????

aryaxt

Newbie
When my first Activity loads i create a service (Socket connection to my server), and this srrvice suppose to keep running while the app is running.
I navigate to other Activities, and I need to somehow get an instant of this Service class to call a method "sendDataToServer".

How can I access a service from my Activity, or any class?
 
Took me a while to work out - just got it to work myself after a few days of searching the web...- just experimenting a bit solved it for me so thought I would share it.

You need to use the android.os.ServiceConnection package when binding your service and adapt your Binder in your service class and use the transact method to communicate between the two.

Heres a simple service

public class MyService extends Service
{
public final IBinder mBinder = new MyBinder();

public class MyBinder implements Binder
{
MyService getService(){
return MyService.this;
}
public String getInterfaceDescription(){
return "My Service Interface";
}
public boolean onTransact(int code, Parcel inData, Parcel outData, int flags){
String inComingString = inData.readString();

/// do your service stuff here....

outData.writeString("response from service");
return true;
}
}

@Override
public void onCreate(){
super.onCreate();
}
@Override
public IBinder onBind(Intent intent){
return mBinder;
}
}



Then, when binding a service use a class the implements service connection.

MyServiceConnection myConnection = new MyServiceConnection()
bindService(new Intent(this, MyService.class),myConnection, BIND_AUTO_CREATE);

public class MyServiceConnection implements ServiceConnection
{
IBinder myBinder;
public void onServiceConnected(ComponentName name,
IBinder binder){
this.myBinder = binder;
}
public void onServiceDisconnected(ComponentName name){
}
public String sendMessage(String message){
try {
Parcel outData = Parcel.obtain();
outData.writeString(message);
Parcel mReply = Parcel.obtain();
// This is the function that actually does coms.
myBinder.transact(IBinder.FIRST_CALL_TRANSACTION,
outData,mReply,0);
// mReply now contains response from service.
return mReply.getString();
} catch (RemoteException re){
return null;
}
}
}

you should then be able to send coms to your service and get its response.

Martin.
 
Thanks a lot for sharing the code.
The way i fixed this issue was by creating everything static in my Service class. even methods.
so when i want to call a method in my service i simply do something like:
MyService.writeData("myString");
but I'm not sure if this is a good practice, it's been working well so far.
 
Back
Top Bottom