无法获得Android原生访问

时间:2016-07-25 12:58:57

标签: android native codenameone

尝试使用本机访问在Android中实现蓝牙功能,但在设备上启动应用程序时,原生访问变量似乎为空。需要帮助弄清楚它为什么会发生以及如何解决它。感谢

这些是我的构建提示 enter image description here

StateMachine类

中的用法示例
    BTNative nativeBT = (BTNative)NativeLookup.create(BTNative.class);
@Override
protected void onMain_ScanButtonAction(Component c, ActionEvent event) {
    super.onMain_ScanButtonAction(c, event);
    try {

        if (nativeBT != null && nativeBT.isSupported()) {

            try {
                nativeBT.findBT();
                nativeBT.openBT();
            } catch (Throwable t) {
                Dialog.show("Error", "Exception during findBT and openBT access: " + t, "OK", null);
            }
        }else{
            Dialog.show("Error", "Can't get native access", "OK", null);
        }

    } catch (Throwable t) {
        Dialog.show("Error", "Exception during native access: " + t, "OK", null);
    }
}

NativeImpl

    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.Intent;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Set;
    import java.util.UUID;
    import android.widget.Toast;
公共类BTNativeImpl {

//android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;

//needed for communication to bluetooth device / network
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;



public void closeBT() {
    try {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//this will send text data to be printed by the bluetooth printer
public void sendData(String param){
    try {
        // the text typed by the user
        param += "\n";
        mmOutputStream.write(param.getBytes());
        // tell the user data were sent
        } catch (Exception e) {
        e.printStackTrace();
    }
}

//this will find a bluetooth printer device
public void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {

          Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "No bluetooth adapter available", Toast.LENGTH_LONG).show();
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            com.codename1.impl.android.AndroidNativeUtil.getActivity().startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().equals("BlueTooth Printer")) {
                    mmDevice = device;
                    break;
                }
            }
        }
        Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "Bluetooth device found.", Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void openBT() {
    try {
        //Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
        beginListenForData();
        Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "Bluetooth Opened", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void beginListenForData() {
    try {
        final Handler handler = new Handler();

        //this is the ASCII code for a newline character
        final byte delimiter = 10;
        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable() {
            public void run() {

                while (!Thread.currentThread().isInterrupted() && !stopWorker) {
                    try {
                        int bytesAvailable = mmInputStream.available();

                        if (bytesAvailable > 0) {

                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for (int i = 0; i < bytesAvailable; i++) {
                                byte b = packetBytes[i];
                                if (b == delimiter) {

                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    // specify US-ASCII encoding
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    // tell the user data were sent to bluetooth printer device
                                    handler.post(new Runnable() {
                                        public void run() {
                                          Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), data, Toast.LENGTH_LONG).show();
                                        }
                                    });
                                } else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }

                    } catch (IOException ex) {
                        stopWorker = true;
                    }

                }
            }
        });

        workerThread.start();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public boolean isSupported() {
    return true;
}

}

1 个答案:

答案 0 :(得分:1)

您可能还需要BLUETOOTH_ADMIN权限。我不确定这是否是唯一的问题,但肯定会引起问题。

来自Android的开发者指南:

https://developer.android.com/guide/topics/connectivity/bluetooth.html#Permissions

在更改impl类的继承以导出Activity时,你也犯了一个大错误!

您需要创建一个单独的活动类,并在创建impl类时单独注册它,Android会创建活动类,两者都不同。我建议看看其他cn1libs,其中大多数是开源的,看看这是怎么做的。我还建议您使用电缆连接设备并以ddms查看输出以跟踪问题。