在其他地方通過ServiceConnection 獲取Service


當我們建立一個服務時,想在其他地方獲取到這個服務的實例時,就需要用到此方法,其中一種寫法如下:

在服務類里建立一個內部類:

1 public class SocketBinder extends Binder { 2         /*返回SocketService 在需要的地方可以通過ServiceConnection獲取到SocketService */
3         public SocketService getService() { 4             return SocketService.this; 5  } 6     }

然后在需要獲取的地方通過ServiceConnection獲取:

 1 ServiceConnection serviceConnection = new ServiceConnection() {  2  @Override  3         public void onServiceConnected(ComponentName name, IBinder service) {  4             SocketService.SocketBinder binder = (SocketService.SocketBinder) (service);  5             mSocketService = binder.getService();  6  }  7 
 8  @Override  9         public void onServiceDisconnected(ComponentName name) { 10             mSocketService = null; 11  } 12     };

最后,直接通過bindService實例對象:

1 if (mSocketIntent == null) {//4.30
2             mSocketIntent = new Intent(this, SocketService.class); 3             bindService(mSocketIntent, serviceConnection, BIND_AUTO_CREATE);//獲取到Socket服務實例
4  } 5 
6 對象:

    private Intent mSocketIntent; 7 private SocketService mSocketService;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM