2016-07-25 38 views
1

Mit dem nativen Zugriff versucht, eine Bluetooth-Funktionalität in Android zu implementieren, aber beim Starten der App auf einem Gerät scheint es, dass die native Zugriffsvariable null ist. Brauchen Sie Hilfe, um herauszufinden, warum es passiert ist und wie Sie es lösen können. DankNative Access von Android kann nicht abgerufen werden

Das sind meine Build enter image description here

Ein Beispiel für den Einsatz in State Klasse Hinweise

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; 

public class 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; 
} 

}

Antwort

1

Sie benötigen wahrscheinlich auch die BLUETOOTH_ADMIN-Berechtigung. Ich bin mir nicht sicher, ob das das einzige Problem ist, aber es würde definitiv Probleme verursachen.

Von Android-Entwicklerhandbuch:

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

Sie haben auch einen großen Fehler in das Erbe des impl Klassenwechsels Activity abzuleiten!

Sie müssen eine separate Aktivitätsklasse erstellen und separat registrieren, während wir die impl-Klasse erstellen. Android erstellt die Aktivitätsklasse und beide sind unterschiedlich. Ich schlage vor, andere cn1libs zu betrachten, von denen die meisten Open Source sind, um zu sehen, wie das gemacht wurde. Ich schlage auch vor, dass Sie Ihr Gerät mit einem Kabel verbinden und die Ausgabe in ddms anzeigen, um Probleme zu verfolgen.

+0

Ich habe ein paar zusätzliche Erkenntnisse hinzugefügt –

+0

@ JamesH @ ShaiAlmog Ich habe versucht, was Sie vorgeschlagen, indem Sie ** com.codename1.impl.android.AndroidNativeUtil.getActivity() ** und nicht die Erweiterung ** Aktivität **, aber jetzt nichts passiert, wenn ich auf die Schaltfläche zum Verbinden klicke. Ich schaute in den ddms und fand, dass Bluetooth Erlaubnis verweigert wurde (wie in der APP nicht Bluetooth Erlaubnis). Aber ich habe die Berechtigungen auch enthalten. – 4bdu1

+0

@ JamesH @ ShaiAlmog Auch auf die Installation der App sehe ich nicht die Bluetooth-Berechtigungen. – 4bdu1