RemoteService.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.ht.gate;
  2. import android.app.Service;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.IBinder;
  8. import android.os.RemoteException;
  9. import android.util.Log;
  10. import android.widget.Toast;
  11. public class RemoteService extends Service {
  12. private static final String TAG = RemoteService.class.getName();
  13. private MyBinder mBinder;
  14. private ServiceConnection connection = new ServiceConnection() {
  15. @Override
  16. public void onServiceConnected(ComponentName name, IBinder service) {
  17. IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
  18. try {
  19. Log.e(TAG, "connected with " + iMyAidlInterface.getServiceName());
  20. } catch (RemoteException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. @Override
  25. public void onServiceDisconnected(ComponentName name) {
  26. Log.e(TAG, "onServiceDisconnected: 链接断开,重新启动 LocalService");
  27. Toast.makeText(RemoteService.this, "链接断开,重新启动 LocalService", Toast.LENGTH_LONG).show();
  28. startService(new Intent(RemoteService.this, LocalService.class));
  29. bindService(new Intent(RemoteService.this, LocalService.class), connection, Context.BIND_IMPORTANT);
  30. }
  31. };
  32. public RemoteService() {
  33. }
  34. @Override
  35. public int onStartCommand(Intent intent, int flags, int startId) {
  36. Log.e(TAG, "onStartCommand: RemoteService 启动");
  37. Toast.makeText(this, "RemoteService 启动", Toast.LENGTH_LONG).show();
  38. bindService(new Intent(this, LocalService.class), connection, Context.BIND_IMPORTANT);
  39. return START_STICKY;
  40. }
  41. @Override
  42. public IBinder onBind(Intent intent) {
  43. mBinder = new MyBinder();
  44. return mBinder;
  45. }
  46. private class MyBinder extends IMyAidlInterface.Stub {
  47. @Override
  48. public String getServiceName() throws RemoteException {
  49. return RemoteService.class.getName();
  50. }
  51. @Override
  52. public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
  53. }
  54. }
  55. }