2017-06-16 5 views
0

Ich habe an einem Bluetooth-Gerät gearbeitet und erstelle eine App dafür.Android: Bluetooth Socket geschlossen

Ich sollte es LED ein oder aus diesen Geräten wenden können, indem er den Code 0 oder 1.

ich einige Fehler haben an Ort und Stelle zu kontrollieren mich mit der Frage zu helfen, und nach Alter und starrte es an kann nicht sehen, wo das Problem liegt.

Ich finde Geräte richtig, und habe die MAC-Adresse des Geräts überprüft, das ist alles in Ordnung. Von dem, was ich mit Logs sehen kann, scheint ich auch alle Sockets korrekt zu öffnen.

Der Fehler tritt in der letzten Phase des Prozesses auf, wenn Bytedaten an das Gerät gesendet werden. Kann jemand etwas entdecken, was ich nicht kann? Vielleicht wird die Verbindung nicht erfolgreich hergestellt?

Um die ausgelöste Ausnahme zu klären, ist in der Methode sendData().

Wenn Sie den Fehler finden, werde ich Sie für immer lieben haha.

Die Fehlermeldung:Fatal Error, In onResume() and an exception occurred during write:socket closed.

Also, was die Buchse schließen, bevor die Daten sendet oder wird nie erfolgreich geöffnet?

Wie auch immer, eine Menge Code-Eingang:

public class ScanFragment extends Fragment { 

    ArrayList<DeviceItem> scannedList; 
    Button scanningButton; 
    TextView scanningText; 
    ListView scannedListView; 
    BluetoothAdapter mBluetoothAdapter; 
    DeviceItem item; 
    DeviceCustomAdapter adapter; 
    BluetoothDevice device; 
    String TAG = "TEST"; 

    private BluetoothAdapter btAdapter = null; 
    private BluetoothSocket btSocket = null; 
    private OutputStream outStream = null; 

    // Intent request codes 
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1; 
    private static final int REQUEST_ENABLE_BT = 3; 

    // Well known SPP UUID 
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    // Insert your bluetooth devices MAC address 
    private static String address = "00:00:00:00:00:00"; 

    public ScanFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     return inflater.inflate(R.layout.fragment_scan, container, false); 
    } 

    @Override 
    public void onDestroy() { 
     getActivity().unregisterReceiver(mReceiver); 
     super.onDestroy(); 
    } 

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      Log.i("found", "hello" + ""); 
      String action = intent.getAction(); 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       device = intent 
         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       item = new DeviceItem(); 
       item.setDeviceName(device.getName()); 
       item.setDeviceCode(device.getAddress()); 
       item.setDeviceId(MY_UUID); 
       scannedList.add(item); 
       Log.i("BT", device.getName() + "\n" + device.getAddress()); 
      } else { 
       Log.i("BT", "none" + ""); 
      } 
      adapter = new DeviceCustomAdapter(
        getActivity().getApplicationContext(), scannedList); 
      scannedListView.setAdapter(adapter); 
     } 
    }; 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onActivityCreated(savedInstanceState); 

     super.onActivityCreated(savedInstanceState); 

     scannedList = new ArrayList<>(); 
     scanningButton = (Button) getActivity().findViewById(R.id.scanningButton); 
     scanningText = (TextView) getActivity().findViewById(R.id.scanningText); 
     scannedListView = (ListView) getActivity().findViewById(R.id.scannedListView); 
     scannedListView.setVisibility(View.VISIBLE); 
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

     if (Build.VERSION.SDK_INT >= 15 && 
       ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); 
     } 

     if (mBluetoothAdapter == null) { 
      scanningText.setText("Your device does not support Bluetooth, Sorry!"); 
     } else if (!mBluetoothAdapter.isEnabled()) { 
      scanningText.setText("You need to enable bluetooth to use this app.."); 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
     } 

     scanningButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       scanningText.setText("Scanning..."); 
       mBluetoothAdapter.startDiscovery(); 
       mBluetoothAdapter.isDiscovering(); 

       scanningText.setText("Click on a device to connect"); 
      } 
     }); 

     // Register for broadcasts when a device is discovered. 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     getActivity().registerReceiver(mReceiver, filter); 

     scannedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       item = scannedList.get(position); 
       String name= scannedList.get(position).getDeviceName(); 
       Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Connecting to " + item.getDeviceCode() + "" + name, Toast.LENGTH_SHORT); 
       toast.show(); 
       scanningText.setText(item.getDeviceCode()); 
       mBluetoothAdapter.cancelDiscovery(); 
       address = item.getDeviceCode(); 
       // Create the result Intent and include the MAC address 
       connectDevice(address, true); 
       ledOff(view); 
      } 
     }); 
    } 

    public void ledOn(View v){ 
     sendData("1"); 
     Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is ON", Toast.LENGTH_SHORT); 
     msg.show(); 
    } 

    public void ledOff(View v){ 
     sendData("0"); 
     Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is OFF", Toast.LENGTH_SHORT); 
     msg.show(); 
    } 


    public void connectToDevice(String adr) { 
     super.onResume(); 

     //enable buttons once connection established. 
//  btnOn.setEnabled(true); 
//  btnOff.setEnabled(true); 

     // Set up a pointer to the remote node using it's address. 
     btAdapter = mBluetoothAdapter; 
     BluetoothDevice device = btAdapter.getRemoteDevice(adr); 

     // Two things are needed to make a connection: 
     // A MAC address, which we got above. 
     // A Service ID or UUID. In this case we are using the 
     //  UUID for SPP. 
     try { 
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { 
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); 
     } 

     // Discovery is resource intensive. Make sure it isn't going on 
     // when you attempt to connect and pass your message. 
     btAdapter.cancelDiscovery(); 

     // Establish the connection. This will block until it connects. 
     try { 
      btSocket.connect(); 
     } catch (IOException e) { 
      try { 
       btSocket.close(); 
      } catch (IOException e2) { 
       errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); 
      } 
     } 

     // Create a data stream so we can talk to server. 
     try { 
      outStream = btSocket.getOutputStream(); 
     } catch (IOException e) { 
      errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + "."); 
     } 
    } 

    private void errorExit(String title, String message){ 
     Toast msg = Toast.makeText(getActivity().getApplicationContext(), title + " - " + message, Toast.LENGTH_SHORT); 
     msg.show(); 
//  finish(); 
    } 

    private void sendData(String message) { 
     byte[] msgBuffer = message.getBytes(); 
     try { 
      outStream.write(msgBuffer); 
     } catch (IOException e) { 
      String msg = "In onResume() and an exception occurred during write: " + e.getMessage(); 
      errorExit("Fatal Error", msg); 
     } 
    } 

    private void connectDevice(String address, boolean secure) { 
     // Get the device MAC address 
     connectToDevice(address); 
     // Get the BluetoothDevice object 
     BluetoothDevice device = btAdapter.getRemoteDevice(address); 
    } 

} 

Antwort

0

Der Sockel schließt gehalten. Ich habe es mit Hilfe dieses Threads behoben.

Link

Verwandte Themen