2016-07-25 88 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