2016-07-25 116 views
1

尝试使用本机访问在android中实现蓝牙功能,但在设备上启动应用程序时,似乎本机访问变量为空。需要帮助弄清楚它为什么发生以及如何解决它。由于无法获取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

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

从Android的开发者指南:

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

也改变了实现类的继承来派生Activity犯了大错!

您需要创建一个单独的活动类,并在创建impl类时单独注册它,Android创建活动类并且两者都不相同。我建议看看其他cn1libs,其中大部分是开源的,看看这是如何完成的。我还建议用一条电缆连接你的设备并以ddms查看输出来跟踪问题。

+0

我添加了一些额外的见解 –

+0

@ JamesH @ ShaiAlmog我尝试了你使用** com.codename1.impl.android.AndroidNativeUtil.getActivity()**建议的内容,而不是扩展** Activity **,但现在什么都没有当我点击按钮进行连接时发生。我看着ddms,发现蓝牙许可被拒绝(因为在应用程序不具有蓝牙许可)。但我也包括了权限.. – 4bdu1

+0

@ JamesH @ ShaiAlmog另外在安装应用程序,我没有看到蓝牙的权限。 – 4bdu1