[英]How to create Android bluetooth native module in react-native or Is there any plugin readily available
我是反應原生的新手。 我正在開發應用程序,它連接到藍牙設備並從中獲取數據。 由於React本機允許創建本機模塊並在React JS中使用它,我正在嘗試創建本機藍牙模塊。 任何人都可以幫助我。
/**
* Created by ravitheja.bandari on 4/4/2016.
*/
public class BluetoothRN extends ReactContextBaseJavaModule implements ActivityEventListener {
// note that webView.isPaused() is not Xwalk compatible, so tracking it poor-man style
private boolean isPaused;
private BluetoothAdapter bluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private Promise bluetoothPromise;
private static final int BLUETOOTH_ENABLE_REQUEST = 1;
private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
private static final String E_FAILED_TO_ENABLE_BLUETOOTH = "E_FAILED_TO_ENABLE_BLUETOOTH";
public BluetoothRN(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "BluetoothAndroid";
}
@ReactMethod
public void getAdapter(){
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
@ReactMethod
public void getBondedDevices(final Promise promise){
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
// Store the promise to resolve/reject when picker returns data
bluetoothPromise = promise;
try {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
currentActivity.startActivityForResult(turnOn, BLUETOOTH_ENABLE_REQUEST);
} catch (Exception e) {
bluetoothPromise.reject(E_FAILED_TO_ENABLE_BLUETOOTH, e);
bluetoothPromise = null;
}
}
private ArrayList getPairedDevices(){
pairedDevices = bluetoothAdapter.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
return list;
}
@Nullable
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
return constants;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
ReactPackage
public class BluetoothReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new BluetoothRN(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return null;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return null;
}
}
re:有沒有隨時可用的插件?
我正在尋找相同的東西並找到了這個:
React Native版本的BluetoothSerial插件。 對於android和ios https://github.com/rusel1989/react-native-bluetooth-serial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.