My *_*God 1 android bluetooth-lowenergy android-bluetooth
我一直在上班时继续学习NoClassDefFoundError.
该代码取自BluetoothLeGatt项目 -
http://developer.android.com/samples/BluetoothLeGatt/project.html
我的代码:
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() { //java.lang.NoClassDefFoundError...
@Override
public void onLeScan(final BluetoothDevice device,
final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String msg= device.getAddress();
Log.d(TAG,msg);
addItems(msg);
}
});
}
};
Run Code Online (Sandbox Code Playgroud)
有人建议错误是因为我的设备不支持BLE但我想为任何设备摆脱这个错误.因此,如果它不支持BLE功能,则只需跳过此错误,否则继续调用此功能BluetoothAdapter.LeScanCallback.
注意:
见这个我以前SO发布更多的澄清.
将BLE功能检查作为第一行onCreate()并不能阻止崩溃 -
@Override
public void onCreate(Bundle savedInstanceState) {
if (!bleCheck()) {
Toast.makeText(getApplicationContext(), R.string.ble_not_supported,
Toast.LENGTH_SHORT).show();
finish();
}
//Rest of the code
//Call to BLE Scan on button click that causes error..
}
private boolean bleCheck() {
boolean result = false;
if (getPackageManager().
hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
result = true;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
由于BluetoothAdapter.LeScanCallback是在API级别18 ; 来源,此代码也需要API级别检查.以下是我如何解决这个问题,并未将回调声明为私有,但条件为:
boolean apiJBorAbove = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2 ? true
: false;
boolean isBleAvailable = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE) ? true : false;
// Use this check to determine whether BLE is supported on the device.
if (isBleAvailable && apiJBorAbove) {
// Initializes a Bluetooth adapter.
// For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled.
// If not, displays a dialog requesting user permission to enable
// Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
}
BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device,
final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String msg= device.getAddress();
// Log.d(TAG,msg);
// addItems(msg);
}
});
}
};
}
Run Code Online (Sandbox Code Playgroud)
这NoClassDefFoundError是由于API,而不是基于PackageManager.FEATURE_BLUETOOTH_LE.
| 归档时间: |
|
| 查看次数: |
2327 次 |
| 最近记录: |