简体   繁体   中英

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

    <?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 . Simply put this code inside your MainActivity .I recently tested it .It,s working. 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

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

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

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

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
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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