Android涓璪indService鎬庝箞浣跨敤
鍦ˋndroid涓紝鎮ㄥ彲浠ヤ娇鐢ㄤ互涓嬫楠ゆ潵浣跨敤bindService锛?/p>
- 鍦ˋctivity鎴朏ragment涓紝鍒涘缓涓€涓猄erviceConnection瀵硅薄锛屽畠灏嗙敤浜庣洃鍚湇鍔$殑杩炴帴鐘舵€佸拰鎺ユ敹鏈嶅姟鐨勫疄渚嬨€?/li>
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// 鍦ㄨ繖閲岃幏鍙栧埌鏈嶅姟鐨勫疄渚?MyService.MyBinder binder = (MyService.MyBinder) iBinder;
MyService service = binder.getService();
// 鍙互鍦ㄨ繖閲岃皟鐢ㄦ湇鍔$殑鏂规硶
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 褰撴湇鍔℃柇寮€杩炴帴鏃惰皟鐢?}
};
- 鍦ˋctivity鎴朏ragment涓紝鍒涘缓涓€涓狪ntent瀵硅薄锛岀敤浜庢寚瀹氳缁戝畾鐨勬湇鍔°€?/li>
Intent intent = new Intent(this, MyService.class);
- 璋冪敤
bindService()
鏂规硶灏咥ctivity鎴朏ragment涓庢湇鍔¤繘琛岀粦瀹氥€?/li>
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
- 鍦ㄤ笉鍐嶉渶瑕佹湇鍔℃椂锛岃皟鐢?code>unbindService()鏂规硶灏咥ctivity鎴朏ragment涓庢湇鍔¤В缁戙€?/li>
unbindService(mServiceConnection);
璇锋敞鎰忥紝bindService鏂规硶鏄竴涓紓姝ユ搷浣滐紝瀹冧細绔嬪嵆杩斿洖锛岃€屼笉浼氱瓑寰呮湇鍔″畬鎴愮粦瀹氥€傚洜姝わ紝鍦?code>onServiceConnected()鏂规硶涓幏鍙栧埌鏈嶅姟鐨勫疄渚嬩箣鍓嶏紝鍙兘闇€瑕佺瓑寰呯墖鍒汇€?/p>
鍚屾椂锛屽湪AndroidManifest.xml鏂囦欢涓紝璁板緱涓鸿缁戝畾鐨勬湇鍔℃坊鍔犻€傚綋鐨勫0鏄庯細
<service android:name=".MyService" />
杩欐牱锛屾偍灏卞彲浠ラ€氳繃bindService鏂规硶鍦ˋndroid涓娇鐢ㄦ湇鍔′簡銆?/p>