How is it better to abstract the mechanism for obtaining methods of a particular MyService , and are there any attempts at all to reduce the repeatability of the code in this case?

The solution is to copy the code for each Service (by android.com/guide ):

 /** Точка доступа к ChatServerService. */ private ChatServerService mChatServerService; /** Точка доступа к ChatClientService. */ private ChatClientService mChatClientService; /** Объект подключения к Service'у ChatServerService */ private final ServiceConnection mServerConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // Получение объекта сервиса при успешном подключении mChatServerService = ((ChatServerService.LocalBinder) service).getService(); }; @Override public void onServiceDisconnected(ComponentName arg0) { Toast.makeText(getBaseContext(), "Неявный разрыв...", Toast.LENGTH_LONG).show(); mChatServerService = null; }; }; /** Объект подключения к Service'у ChatClientService */ private final ServiceConnection mClientConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // Получение объекта сервиса при успешном подключении mChatClientService = ((ChatClientService.LocalBinder) service).getService(); }; @Override public void onServiceDisconnected(ComponentName arg0) { Toast.makeText(getBaseContext(), "Неявный разрыв...", Toast.LENGTH_LONG).show(); mChatClientService = null; }; }; 

1 answer 1

Why are you making ServiceConnection an anonymous class? Make your class implement ServiceConnection interface, like:

 public class MyServiceConnection implements ServiceConnection { private Class<?> myServiceBinderClz; private Service myService; public MyServiceConnection(Class<?> myServiceBinderClz) { this.myServiceBinderClz=myServiceBinderClz; } @Override public void onServiceConnected(ComponentName className, IBinder service) { myService = ((myServiceBinderClz) service).getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { myService=null; } public Service getService() {return myService;} } 

Then we call the type:

 MyServiceConnection myServiceConnection = new MyServiceConnection(ServerChatService.LocalBinder.class); mServerChatService=myServiceConnection.getService(); 

Please do not beat with your feet, if not compiled. There are definitely syntax errors - only an idea is presented here.

  • 1) ServiceConnection is made anonymous class only because it is the default implementation offered in the android.com guide; 2) when logging in through Class<?> You can’t reach LocalBinder.getService() . - Artyom Ionash
  • Well, yes, I agree. Modify the code :) I just illustrated the idea - Barmaley