如何在Android中将BluetoothGatt和特性传递给AsyncTask?

时间:2015-02-12 11:11:29

标签: android android-asynctask bluetooth-lowenergy

我想使用AsyncTask来实施mGatt.writeCharacteristic

首先,我尝试将mBluetoothGattBluetoothGattCharacteristic传递给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中将CharacteristicAsyncTask传递给Android

2 个答案:

答案 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) {
    }
}