Last active
February 17, 2022 06:59
-
-
Save itstartstosnow/5461e8d674630a95fb1ae304b2f8a4cf to your computer and use it in GitHub Desktop.
Android basic bind a service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
MyService.ServiceBinder mBinderService; | |
ServiceConnection mServConn = new ServiceConnection() { | |
@Override | |
public void onServiceConnected(ComponentName name, IBinder service) { | |
mBinderService = (MyService.ServiceBinder) service; | |
// later call the binder to do something | |
mBinderService.someInterface(0); | |
} | |
@Override | |
public void onServiceDisconnected(ComponentName name) { | |
} | |
}; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
Intent intent = new Intent(MainActivity.this, MyService.class); | |
bindService(intent, mServConn, BIND_AUTO_CREATE); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyService extends Service { | |
public ServiceBinder mBinder = new ServiceBinder(); | |
public MyService() { | |
} | |
@Override | |
public IBinder onBind(Intent intent) { | |
return mBinder; | |
} | |
public class ServiceBinder extends Binder { | |
public void someInterface(int i) { | |
// do something, called by client | |
} | |
public MyService getService() { | |
// can also return this service so that client can all its any public method | |
return MyService.this; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment