2016-02-29 96 views
0

因此,我試圖通過AlertDialog將我的配對設備連接到我的應用程序中。但是當我選擇我想連接的設備時沒有任何反應。我是否在我的代碼中缺少需要添加以進行連接的內容?無法通過藍牙連接到AlertDialog中列出的配對設備

MainActivity:

package com.example.asabanov.powersupplytool; 

import android.app.AlertDialog; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Toast; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Set; 
import java.util.UUID; 

public class MainActivity extends AppCompatActivity { 
    BluetoothAdapter btAdapter; 
    Button b1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     b1 = (Button) findViewById(R.id.connect); 
     btAdapter = BluetoothAdapter.getDefaultAdapter(); 
     //init(); 

     if (btAdapter == null) { 
      Toast.makeText(getApplicationContext(), "Device does not Support Bluetooth", Toast.LENGTH_LONG).show(); 
      finish(); 
     } else { 
      if (!btAdapter.isEnabled()) { 
       Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(intent, 1); 
      } 
     } 
    } 

    public void onClick(View v) { 

     int id = v.getId(); 
     switch (id) { 
      case R.id.connect: 
       onConnect(); //Operation 
       Log.i("Log", "Pressed onClick"); 
       break; 
      default: 
       break; 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_CANCELED) { 
      Toast.makeText(getApplicationContext(), "Bluetooth must be Enabled", Toast.LENGTH_SHORT).show(); 
      finish(); 
     } 
    } 

    private void onConnect() { 
     ArrayList deviceStrs = new ArrayList(); 
     final ArrayList<String> devices = new ArrayList(); 

     BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); 
     Set pairedDevices = btAdapter.getBondedDevices(); 
     if (pairedDevices.size() > 0) { 
      for (Object device : pairedDevices) { 
       BluetoothDevice bdevice = (BluetoothDevice) device; 
       deviceStrs.add(bdevice.getName() + "\n" + bdevice.getAddress()); 
       devices.add(bdevice.getAddress()); 
      } 
     } 

     // show list 
     final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); 

     ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice, 
       deviceStrs.toArray(new String[deviceStrs.size()])); 

     alertDialog.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
       int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); 
       String deviceAddress = devices.get(position); 

       BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); 
       BluetoothDevice device = btAdapter.getRemoteDevice(deviceAddress); 
       UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//AA:BB:CC:11:22:33"); 
       try { 
        BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid); 
        socket.connect(); 
       } catch (IOException e) { 
       } 
      } 
     }); 


     alertDialog.setTitle("Connect"); 
     alertDialog.show(); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, 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 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

activity_main:

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_w 

idth="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.asabanov.powersupplytool.MainActivity"> 

    <Button 
     android:id="@+id/connect" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onClick" 
     android:text="@string/connect_btn" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 

</RelativeLayout> 
+1

您可能會錯過一個可能幫助您解決問題的異常。打印通過'e.printStackTrace()'連接設備時捕獲的異常' –

+0

我編輯了OP。看看Logcat,看看你能發現什麼。 – swess

回答

0

所以我解決了這個問題......問題是我愚蠢,試圖連接到一個不支持UUID的設備......我打印了它得到的結果並將它連接到了OBDII模塊。

try { 
        BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid); 
        socket.connect(); 
        Log.v("connect", "connect"); //this, 
       } 
       catch (IOException e) { 
        e.printStackTrace(); //this 
        Log.v("exception","e"); //and this 
       } 
0

你應該實現一個BroadcastReceiver接收關於藍牙狀態信息,並打印出來,然後你就會知道哪些步驟錯誤發生。

+0

我不會遇到任何錯誤。我想我沒有在配對設備之間建立連接的代碼實現,我不知道如何實現它。 – swess

+0

是的,我知道你的意思。當你連接到另一個藍牙設備時,你可以知道關於連接過程的詳細信息。例如,沒有找到設備,設備沒有綁定,設備連接錯誤等等。所以你應該首先知道什麼是問題。 – wngxao

+0

Aaah確定了!問問你能不能幫我解決這個問題?在我的代碼中實現廣播接收器?我並不是那麼有經驗。我會非常感謝 – swess

0

你只是想配對devices.You不需要採取UUID。只需將此代碼放入您的MainActivity。我最近測試了它,它正在工作。 您可以查看註釋以瞭解正確的代碼流程。請記住在清單文件中提供權限。

`

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.ProgressBar; 
import android.widget.Toast; 
import java.lang.reflect.Method; 
import java.util.Set; 
public class MainActivity extends AppCompatActivity { 
int REQUEST_ENABLE_BT =1 ; 
Button scan; 
private ProgressBar spinner; 
private ArrayAdapter<String> mArrayAdapter; 
private ArrayAdapter<String> mArrayAdapter2; 
private ListView btList2; 
private ListView btList; 




final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

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


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

    scan=(Button)findViewById(R.id.scan); 
    spinner=(ProgressBar) findViewById(R.id.pbar); 
    spinner.setVisibility(View.GONE); 
    //progress bar visibilty 


    btList = (ListView) findViewById(R.id.dlist); 
    btList2 = (ListView) findViewById(R.id.dlist1); 
    mArrayAdapter = new ArrayAdapter<String> (this,R.layout.device_list,R.id.dText); 
    mArrayAdapter2 = new ArrayAdapter<String>(this,R.layout.device_list,R.id.dText); 
    btList.setAdapter(mArrayAdapter); 
    btList2.setAdapter(mArrayAdapter2); 




    if (mBluetoothAdapter == null) { 

     Toast.makeText(getApplicationContext(), "Device does not support Bluetooth",Toast.LENGTH_LONG).show(); 
     // Device does not support Bluetooth 
    } 

    if(!mBluetoothAdapter.isEnabled()){ 

     Toast.makeText(getApplicationContext(), "Turn ON Bluetooth",Toast.LENGTH_LONG).show(); 

     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 

     // Request user to Turn on Bluetooth 

    } 


    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); 



    scan.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      spinner.setVisibility(View.VISIBLE); 
      spinner.setProgress(10); 
      mBluetoothAdapter.startDiscovery(); 


      //set visible progress bar onclick scan button 
     } 


    }) ; 

    btList2.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    // Cancel discovery because it's costly and we're about to connect 
      mBluetoothAdapter.cancelDiscovery(); 
      String value=mArrayAdapter2.getItem(position); 
      int index=value.indexOf(",")+1; 
      BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(value.substring(index, value.length()).trim()); 
      if (device.getBondState() == BluetoothDevice.BOND_BONDED) { 
       unpairDevice(device); //it unpair device on click if device is already paired 
      } else { 
       pairDevice(device);//it pairs devices present in array list on click 
      } 
     } 


    }); 

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
       // If there are paired devices 
    if (pairedDevices.size() > 0) 
    { 
     for (BluetoothDevice device : pairedDevices) { 
       // Add the name and address to an array adapter to show in a ListView 
      mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 

     }} 

} 

// Create a BroadcastReceiver for ACTION_FOUND 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 



    public void onReceive(Context context, Intent intent) { 

     String action = intent.getAction(); 
     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // Add the name and address to an array adapter to show in a ListView 
      mArrayAdapter2.add(device.getName()+"," + "\n" + device.getAddress()); 
      mArrayAdapter2.notifyDataSetChanged(); 



     } 
    } 
}; 




private void pairDevice(BluetoothDevice device) { 

    try { 

     Method m = device.getClass() 
       .getMethod("createBond", (Class[]) null); 
     m.invoke(device, (Object[]) null); 
    } catch (Exception e) { 
     Log.e("pairDevice()", e.getMessage()); 
    } 
} 

private void unpairDevice(BluetoothDevice device) { 
    try { 
     Method m = device.getClass() 
       .getMethod("removeBond", (Class[]) null); 
     m.invoke(device, (Object[]) null); 
    } catch (Exception e) { 
     Log.e("unpairDevice()", e.getMessage()); 
    } 
}}` 

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.oit.demo_blu.MainActivity" 
android:orientation="vertical" 
> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/Hello" 

    /> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/scan" 
    android:text="SCAN For New Devices" 

    /> 

<ProgressBar 
    android:id="@+id/pbar" 
    style="?android:attr/progressBarStyle" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginLeft="30dp" 

    /> 

</LinearLayout> 

<ListView 
    android:tag="New Devices" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/dlist1" 
    ></ListView> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Paired Devices. . ." 

    /> 

<ListView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/dlist" 

    > 

</ListView> 

+0

您可以看到我創建了配對設備和配對設備...並稱爲配對設備()與可用設備配對。細節在這裏給出[http://developer.android.com/guide/topics/connectivity/bluetooth.html] –

+0

我正在製作一個OBDII應用程序,並且UUID是必需的。但是,代碼中的哪一部分會與設備建立連接,以便我可以將其放入我的設備? – swess

+0

請讓我知道,如果您的代碼運行成功:) –

0

確定。在AndroidManifest.xml

<receiver 
     android:name="hust.b538.Bluetooth.BluetoothManager$BluetoothBroadcastReceiver"> 
     <intent-filter> 
      <action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED"/> 
      <action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED"/> 
      <action android:name="android.bluetooth.device.action.FOUND"/> 
      <action android:name="android.bluetooth.device.action.UUID"/> 
      <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED"/> 
      <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"/> 
      <category android:name="android.intent.category.DEFAULT"/> 
     </intent-filter> 
    </receiver> 

步驟2中,添加權限:: 步驟1中,在AndroidManifest.xml添加接收機

<uses-permission android:name="android.permission.BLUETOOTH"/> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/> 

步驟3中,創建所述接收器類:

public class BluetoothBroadcastReceiver extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    if (action == BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) { 
     Bundle bundle=intent.getExtras(); 
     BluetoothDevice bt=bundle.getParcelable(BluetoothDevice.EXTRA_DEVICE); 
     if(bundle.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE)==BluetoothAdapter.STATE_CONNECTED){ 
      Log.e("bluetooth connection state", "connected"); 
     }else if(bundle.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE)==BluetoothAdapter.STATE_CONNECTING){ 
      Log.e("bluetooth connection state", "connecting"); 
     }else if(bundle.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE)==BluetoothAdapter.STATE_DISCONNECTED){ 
      Log.e("bluetooth connection state", "disconnected"); 
     } 
    } else if (action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) { 
     Bundle bundle=intent.getExtras(); 
     BluetoothDevice bt=bundle.getParcelable(BluetoothDevice.EXTRA_DEVICE); 
     if(bundle.getInt(BluetoothDevice.EXTRA_BOND_STATE)==BluetoothDevice.BOND_NONE){ 
     }else if(bundle.getInt(BluetoothDevice.EXTRA_BOND_STATE)==BluetoothDevice.BOND_BONDING){ 
     }else if(bundle.getInt(BluetoothDevice.EXTRA_BOND_STATE)==BluetoothDevice.BOND_BONDED){ 
     } 
    } else if (action == BluetoothDevice.ACTION_UUID) { 
    } 
} 
} 

就這樣。

+0

嘿!我更新了OP。在Logcat中是錯誤的。 – swess