2016-01-07 163 views
0

直到現在我的應用程序可以發現使可發現和所有這些。當我按設備的名稱,例如我的手機附近(我已打開藍牙),它出現在我的listview事實上,我想當我按它,我有經典的錯誤< <「W/BluetoothAdapter:getBluetoothService()調用沒有BluetoothManagerCallback W/System.err:java.io.IOException:讀取失敗,套接字可能關閉或超時,讀取ret :-1「>>。它不能在我的代碼中工作bluetoothSocket.connect。 在其他情況下,當我用我的平板電腦(其中包括我的android工作室應用程序)進入我的汽車時,我可以搜索obd2,並且當我按下它時,它會生成債券需求。我鍵入1234密碼並製作債券在平板電腦藍牙功能,我可以看到它。我需要有人做了這樣的事情來幫助我進行下一步。例如,如何發送一個命令轉速或速度,並採取相應的措施。請幫助我!安卓與obd2的藍牙連接

這是我的代碼:

公共類BluetoothActivity延伸AppCompatActivity {

private static final String TAG ="msg" ; 
private BluetoothAdapter bluetoothAdapter; 
private ToggleButton toggleButton; 
private ListView listview; 
private ArrayAdapter adapter; 
private static final int MESSAGE_READ =1; 
private static final int ENABLE_BT_REQUEST_CODE = 1; 
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2; 
private static final int DISCOVERABLE_DURATION = 300; 
private final static UUID uuid = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); 

// Create a BroadcastReceiver for ACTION_FOUND 
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     // Whenever a remote Bluetooth device is found 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // Add the name and address to an array adapter to show in a ListView 
      adapter.add(bluetoothDevice.getName() + "\n" 
        + bluetoothDevice.getAddress()); 
      adapter.notifyDataSetChanged(); 
     } 
     //uuid=BluetoothDevice.getUuids()[0].getUuid(); 
    } 
}; 

// IntentFilter的過濾器=新的IntentFilter(BluetoothDevice.ACTION_FOUND);

// registerReceiver(廣播接收器,過濾器)//不要忘記的onDestroy

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_bluetooth); 

    toggleButton = (ToggleButton) findViewById(R.id.toggleButton); 

    listview = (ListView) findViewById(R.id.listView); 


    //Listview Item Click Listener 
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      String itemValue = (String) listview.getItemAtPosition(position); 
      String MAC = itemValue.substring(itemValue.length() - 17); 
      BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC); 
      // Initiate a connection request in a separate thread 
      ConnectingThread t = new ConnectingThread(bluetoothDevice); 
      t.start(); 
     } 
    }); 

    adapter = new ArrayAdapter 
      (this, android.R.layout.simple_list_item_1); 
    listview.setAdapter(adapter); 

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

} 

//Οταν πατάμε το button για να ανοίξει το bluetooth! 
public void onToggleClicked(View view) { 

    adapter.clear(); 

    ToggleButton toggleButton = (ToggleButton) view; 
    if (bluetoothAdapter == null) { 
     // Device does not support Bluetooth 
     Toast.makeText(getApplicationContext(), "Η συσκευή δεν υποστηρίζει bluetooth.", 
       Toast.LENGTH_SHORT).show(); 
     toggleButton.setChecked(false); 
    } else { 

     if (toggleButton.isChecked()){ // to turn on bluetooth 
      if (!bluetoothAdapter.isEnabled()) { 
       // A dialog will appear requesting user permission to enable Bluetooth 
       Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE); 
      } else { 
       Toast.makeText(getApplicationContext(), "Η Συσκευή είναι έτοιμη για χρήση." + 
           "\n" + "Ανίχνευση για Απομακρυσμένες Συσκευές...", 
         Toast.LENGTH_SHORT).show(); 
       // To discover remote Bluetooth devices 
       discoverDevices(); 
       // Make local device discoverable by other devices 
       makeDiscoverable(); 
      } 
     } else { // Turn off bluetooth 

      bluetoothAdapter.disable(); 
      adapter.clear(); 
      Toast.makeText(getApplicationContext(), "Η συσκευή έχει Απενεργοποιηθεί.", 
        Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

public void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (requestCode == ENABLE_BT_REQUEST_CODE) { 

     // Bluetooth successfully enabled! 
     if (resultCode == Activity.RESULT_OK) { 
      Toast.makeText(getApplicationContext(), "Το Bluetooth έχει Ενεργοποιηθεί." + 
          "\n" + "Ανίχνευση για Απομακρυσμένες Συσκευές...", 
        Toast.LENGTH_SHORT).show(); 

      // To discover remote Bluetooth devices 
      discoverDevices(); 

      // Make local device discoverable by other devices 
      makeDiscoverable(); 
       // Start a thread to create a server socket to listen 
      // for connection request 
      ListeningThread t = new ListeningThread(); 
      t.start(); 


     } else { // RESULT_CANCELED as user refused or failed to enable Bluetooth 
      Toast.makeText(getApplicationContext(), "Το Bluetooth δεν έχει Ενεργοποιηθεί.", 
        Toast.LENGTH_SHORT).show(); 

      // Turn off togglebutton 
      toggleButton.setChecked(false); 
     } 
    } else if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){ 

     if (resultCode == DISCOVERABLE_DURATION){ 
      Toast.makeText(getApplicationContext(), "Η συσκευή είναι τώρα Ανιχνεύσιμη απο άλλες συσκευές.. " + 
          DISCOVERABLE_DURATION + " Δευτερόλεπτα", 
        Toast.LENGTH_SHORT).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), "Αποτυχία να Ενεργοποιηθεί η Ανιχνευσημότητα της Συσκευής.", 
        Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

protected void discoverDevices(){ 
    // To scan for remote Bluetooth devices 
    if (bluetoothAdapter.startDiscovery()) { 
     Toast.makeText(getApplicationContext(), "Ανίχνευση για άλλες Συσκευές Bluetooth...", 
       Toast.LENGTH_SHORT).show(); 
    } else { 
     Toast.makeText(getApplicationContext(), "Η Ανίχνευση Απέτυχε να αρχίσει.", 
       Toast.LENGTH_SHORT).show(); 
    } 
} 
//Συνάρτηση για makeDiscoverable 
protected void makeDiscoverable(){ 
    // Make local device discoverable 
    Intent discoverableIntent = new 
      Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION); 
    startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    // Register the BroadcastReceiver for ACTION_FOUND 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    this.registerReceiver(broadcastReceiver, filter); 
} 
//on pause an xreiastei na bei kwdikas{} 
@Override 
protected void onPause() { 
    super.onPause(); 
    this.unregisterReceiver(broadcastReceiver); 
} 
@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.bluetooth, menu); 
      return true; 
      } 
@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

//Thread gia ton server.. 
private class ListeningThread extends Thread { 
    private final BluetoothServerSocket bluetoothServerSocket; 
    //Constructor 
    public ListeningThread() { 
     BluetoothServerSocket temp = null; 
     try { 
      temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     bluetoothServerSocket = temp; 
    } 

    public void run() { 
     BluetoothSocket bluetoothSocket = null; 
     // This will block while listening until a BluetoothSocket is returned 
     // or an exception occurs 
     Log.d(TAG, "O kwdikas edw trexei"); 
     while (true) { 
      try { 
       bluetoothSocket = bluetoothServerSocket.accept(); 
      } catch (IOException e) { 
       break; 
      } 

      // If a connection is accepted 
      if (bluetoothSocket != null) { 
       //!!!!!!!!!!!!!!!! 
       runOnUiThread(new Runnable() { 
       public void run() { 
       Toast.makeText(getApplicationContext(), "Επιτυχής Σύνδεση με την συσκευή.", 
         Toast.LENGTH_SHORT).show(); 
        } 

       }); 
       ConnectedThread a = new ConnectedThread(bluetoothSocket); 
        a.start(); 
       try { 
        bluetoothServerSocket.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       break; 

      } 
     } 
    } 

    public void cancel() { 
     try { 
      bluetoothServerSocket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

    private class ConnectingThread extends Thread{ 
     private final BluetoothSocket bluetoothSocket; 
     private final BluetoothDevice bluetoothDevice ; 

     public ConnectingThread(BluetoothDevice device){ 
      BluetoothSocket temp = null; 
      bluetoothDevice = device; 
      //Get a BluetoothSocket to connect with the given BluetoothDevice 
      try{ 

     temp=bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); 

      }catch (IOException e){ 
       e.printStackTrace(); 
      } 
      bluetoothSocket = temp; 

      } 


     public void run() { 

      // Cancel discovery as it will slow down the connection 
      bluetoothAdapter.cancelDiscovery(); 
      try { 

       bluetoothSocket.connect(); 
       Log.d(TAG, "the code is running"); 
       // This will block until it succeeds in connecting to the device 
       // through the bluetoothSocket or throws an exception 
       // bluetoothSocket.connect(); 
       //isConnected = true; 
      } catch (IOException connectException) { 
       connectException.printStackTrace(); 
       try { 
        //unable to connect 

        bluetoothSocket.close(); 
       } catch (IOException closeException) { 
        closeException.printStackTrace(); 
       } 
      } 
      // Do work to manage the connection (in a separate thread) 
      //manageConnectedSocket(bluetoothSocket); 
      ConnectedThread t= new ConnectedThread(bluetoothSocket); 
      t.start(); 

     } 



    // Cancel an open connection and terminate the thread 
    public void cancel() { 
     try { 
      bluetoothSocket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
private class ConnectedThread extends Thread { 


    private final BluetoothSocket bluetoothSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 
    private android.os.Handler mHandler; 

    public ConnectedThread(BluetoothSocket socket) { 
     bluetoothSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     byte[] buffer = new byte[1024]; // buffer store for the stream 
     int bytes; // bytes returned from read() 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 
       // Send the obtained bytes to the UI activity 

       mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 
       break; 
      } 
    } 

    // Call this from the main activity to send data to the remote device 
    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 
     } catch (IOException e) { } 
    } 

    // Call this from the main activity to shutdown the connection 
    public void cancel() { 
     try { 
      bluetoothSocket.close(); 
      mmInStream.close(); 
      mmOutStream.close(); 
     } catch (IOException e) { } 
    } 

    public void setmHandler(Handler mHandler) { 
     this.mHandler = mHandler; 
    } 
} 

}

回答

1

您已經能夠一對插入診斷端口的OBDII適配器期間註銷在車上用手機,但現在你需要連接到它。

連接到與該設備:

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); 

    BluetoothDevice device = btAdapter.getRemoteDevice(deviceAddress); 

    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid); 

    socket.connect(); 

一旦連接到與AT命令可以初始化OBDII適配器的設備,如「AT E0」用於回聲關閉,「AT L0」爲換行。

然後,您可以通過發出相應的PID代碼來連續從車輛獲取數據:對於RPM使用「01 0C」,對於速度使用「01 0D」。

http://blog.lemberg.co.uk/how-guide-obdii-reader-app-development

這裏是一個很好的OBD2啓動庫的鏈接,你可以擴展和改善您的特殊需求:

https://github.com/pires/obd-java-api

更多細節和討論可以在這個鏈接找到