android蓝牙库 - 移植到jni

时间:2014-01-18 16:57:41

标签: android bluetooth java-native-interface native porting

我正在大学的一个项目工作。我的教授希望我移植他的android库以使用JNI。据我读过几个网站,据说当我想访问蓝牙,wifi等时我不应该去原生。这是我需要移植的类之一。我认为这门课应该保持这种方式而不是原生。 任何人对我有任何想法/建议? 谢谢

package org.morphone.sense.bluetooth;

import java.util.Set;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;


public class BluetoothSense implements BluetoothSenseInterface {

    private BluetoothAdapter bluetoothAdapter = null;

    public BluetoothSense(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
    }

    @Override
    public Set<BluetoothDevice> getBondedDevices() throws BluetoothSenseException {
        try{
            return bluetoothAdapter.getBondedDevices();
        }catch (Exception e) {
            throw new BluetoothSenseException("Error while getting BondedDevices (" + e.getMessage() + ")");
        }
    }

    @Override
    public int getState() throws BluetoothSenseException{
        try{
            return bluetoothAdapter.getState();
        }catch (Exception e) {
            throw new BluetoothSenseException("Error while getting State (" + e.getMessage() + ")");
        }
    }

    @Override
    public boolean isActive() throws BluetoothSenseException{
        try{
            if (this.getState()!= BluetoothAdapter.STATE_OFF && 
                this.getState()!= BluetoothAdapter.STATE_TURNING_OFF)
                return true;
            else 
                return false;
        }catch (Exception e) {
            throw new BluetoothSenseException("Error while getting isActive (" + e.getMessage() + ")");
        }
    }

}

1 个答案:

答案 0 :(得分:0)

可以在C ++中完全实现org.morphone.sense.bluetooth.BluetoothSense,但是它仍然会使用Java android.bluetooth.BluetoothAdapter,因此如果没有有效使用它会带来零性能提升,例如:如果bluetoothAdapter.getState()被调用的频率超过必要的话。

请注意,Java代码也可能有很多性能改进。例如,如果重写如下,BluetoothSense.isActive()方法的功效将是其两倍:

@Override
public boolean isActive() throws BluetoothSenseException {
    try {
        int state = getState();
        if (state != BluetoothAdapter.STATE_OFF && 
            state != BluetoothAdapter.STATE_TURNING_OFF)
            return true;
        else 
            return false;
    } catch (Exception e) {
        throw new BluetoothSenseException("Error while getting isActive (" + e.getMessage() + ")");
    }
}

如果在应用中没有经常调用isActive(),那么这种变化是不值得的。