无法通过蓝牙连接到 AlertDialog 中列出的配对设备

Unable to connect to paired devices listed in AlertDialog through Bluetooth

所以我正在尝试通过 AlertDialog 在我的应用程序中连接我的配对设备。但是当我选择要连接的设备时没有任何反应。我的代码中是否缺少需要添加以建立连接的内容?

主要活动:

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>

你应该实现一个BroadcastReceiver来接收关于蓝牙状态的信息,并打印它们,然后你就会知道错误发生在哪一步。

你只是想配对 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>

好的。 第一步,在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步,在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步,创建接收器class:

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) {
    }
}
}

就这些了。

所以我解决了这个问题...问题是我很笨并尝试连接到不支持 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
                }