我想使用AsyncTask
来实施mGatt.writeCharacteristic
。
首先,我尝试将mBluetoothGatt
和BluetoothGattCharacteristic
传递给AsyncTask
,如下面的代码所示。
private static BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic HueCharacteristic;
new WriteCharacteristic().execute(mBluetoothGatt , HueCharacteristic);
private class WriteCharacteristic extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
BluetoothGatt gatt = params[0];
BluetoothGattCharacteristic characteristic = params[1];
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
}
}
但我不知道如何在AsyncTask<String, Void, String>
验证参数。我试过AsyncTask<BluetoothGatt, Void, String>
,但它有错误。
如何在BluetoothGatt
中将Characteristic
和AsyncTask
传递给Android
?
答案 0 :(得分:0)
在AsyncTask中编写自己的构造函数。像这样:
private class WriteCharacteristic extends AsyncTask<String, Void,String> {
public WriteCharacteristic(String a, int b) {
//do something with the variables. Save them, whatever
}
@Override
protected String doInBackground(String... urls) {
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
}
}
你可以这样称呼它:
new WriteCharacteristic("a",1).execute();
答案 1 :(得分:0)
AsyncTasks不太好用,因为在配置更改时它们会消失,这就是你能做的事情
private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic HueCharacteristic;
public MyDataObject {
public MyDataObject(BluetoothGatt gatt, BluetoothGattCharacteristic, ch) {
this.gatt = gatt; this.ch = ch;
public BluetoothGatt gatt;
public BluetoothGattCharacteristic ch;
}
new WriteCharacteristic().execute(new MyDataObject(mBluetoothGatt, HueCharacteristic));
private class WriteCharacteristic extends AsyncTask<MyDataObject , Void, String> {
@Override
protected String doInBackground(MyDataObject... data) {
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
}
}