簡體   English   中英

無法通過藍牙連接到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來接收有關藍牙狀態的信息並進行打印,然后您將知道錯誤發生在哪一步。

您只想配對設備,而無需使用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>

好。 步驟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>

步驟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"/>

第三步,創建接收器類:

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
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM