简体   繁体   English

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

[英]Unable to connect to paired devices listed in AlertDialog through Bluetooth

So i'm trying to connect my paired devices in my app through a AlertDialog. 因此,我试图通过AlertDialog连接我的配对设备。 But nothing happens when i'm selecting the device I want to connect to. 但是,当我选择要连接的设备时,没有任何反应。 Am I missing something in my code that needs to be added to make a connection? 我是否在代码中丢失了需要添加才能建立连接的内容?

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: 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来接收有关蓝牙状态的信息并进行打印,然后您将知道错误发生在哪一步。

You simply wants to pair devices.You need not to take UUID . 您只想配对设备,而无需使用UUID Simply put this code inside your MainActivity .I recently tested it .It,s working. 只需将这段代码放入MainActivity中即可 。我最近对其进行了测试。 You can check the comments to understand proper flow of code. 您可以检查注释以了解正确的代码流程。 Remember to give permissions in manifest files. 记住要在清单文件中授予权限。

` `

 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 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>

Ok. 好。 step 1,add receiver in AndroidManifest.xml: 步骤1,在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>

step 2,add permission in AndroidManifest.xml: 步骤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"/>

step 3, create the receiver 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) {
    }
}
}

That's all. 就这样。

So I fixed the issue... The issue was that I was being dumb and trying to connect to a device that does not support the UUID... I printed the results it got and it connected to the OBDII module. 所以我解决了这个问题。问题是我很笨,试图连接到不支持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
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM