私のプロジェクトでは、mCmdBinder.gattConnect()
andmCmdBinder.gattClose()
メソッドを複数回呼び出して、複数のBluetoothGatt
インスタンスを生成しました。ダンプされたファイルに、オブジェクト.hprof
の複数のインスタンスが存在することがわかります。BluetoothGatt
コマンドを実行してもinitiate gc
、これらのインスタンスは消去されません。これらのインスタンスを解放できないのはなぜですか?
MyGattService.java
public class MyGattService extends Service {
private BluetoothAdapter mAdapt;
private BluetoothDevice mDevice;
private BluetoothGatt mGatt;
@Override
public void onCreate() {
super.onCreate();
Log.e("mLog", "service oncreate !");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("mLog", "service ondestroy()!");
}
@Override
public IBinder onBind(Intent intent) {
return new CmdBinder();
}
//发送各种命令
public class CmdBinder extends Binder {
public void gattClose() {
if (mGatt != null) {
mAdapt = null;
mDevice = null;
mGatt.close();
mGatt = null;
Log.e("mLog", "gatt close! mGatt=" + mGatt);
}
}
public void gattConnect() {
mAdapt = BluetoothAdapter.getDefaultAdapter();
mDevice = mAdapt.getRemoteDevice("F4:04:4C:0C:81:1B");
Log.e("mLog", "device bind status:" + mDevice.getBondState());
mGatt = mDevice.connectGatt(MyGattService.this, true, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.e("mlog", "status:" + status + "; newState:" + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.e("mLog", " go discover services!");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e("mLog", "mGatt=" + mGatt);
}
}
});
Log.e("mLog", "gatt connect!");
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* 蓝牙处理放在service中
*/
private MyGattService.CmdBinder mCmdBinder;
private MyGattServiceConnection conn;
public class MyGattServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder service) {
mCmdBinder = (MyGattService.CmdBinder) service;
Log.e("mLog", "service connected!");
}
public void onServiceDisconnected(ComponentName name) {
Log.e("mLog", "service disconnected!");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
Intent gattService = new Intent(MainActivity.this, MyGattService.class);
conn = new MyGattServiceConnection();
bindService(gattService, conn, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn);
}
public void initView() {
TextView retxt = (TextView) findViewById(R.id.txt_reconnect);
retxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCmdBinder.gattConnect();
}
});
TextView close = (TextView) findViewById(R.id.txtclose);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCmdBinder.gattClose();
}
});
}
}