簡體   English   中英

我正在嘗試在 Android Studio 中實現藍牙功能,需要一些幫助來解決連接問題

[英]I'm trying to implement Bluetooth functionality in Android Studio, need some help in connecting problem

我使用藍牙 API 和以下代碼用於開/關、顯示配對設備列表和連接配對設備。 其他功能運行良好,但連接設備不起作用。 我嘗試使用雙向線程,當藍牙打開時,serverthread(acceptthread) 生成並啟動。 當我在列表中選擇設備時,clientthread(connectthread) 生成並啟動。 這是我的意圖,但是當我嘗試在手機上連接時,應用程序被關閉(幾乎在客戶端,偶爾在服務器上)。 我想可能是 UUID 問題所以我檢查了 UUID 00 enter code here 001101-0000-1000-8000-00805F9B34FB,但它沒有幫助。 enter code here抱歉導入代碼塊,非常感謝您的幫助。

'''
package com.practice.bluetoothmodule;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    TextView bthStatus;
    Button bthOn;
    Button bthOff;
    Button bthCon;

    BluetoothAdapter bthAdapter;
    Set<BluetoothDevice> pairedDevices;
    List<String> listofPairedDevices;
    private String btAddress=null;

    BluetoothDevice bthDevice;

    AcceptThread acceptThread;
    ConnectThread connectThread;
    private Handler mHandler = null;

    final static int BT_REQUEST_ENABLE=1;
    final static UUID BT_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

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

        bthStatus = (TextView)findViewById(R.id.text_check);
        bthOn = (Button)findViewById(R.id.bth_on);
        bthOff=(Button)findViewById(R.id.bth_off);
        bthCon=(Button)findViewById(R.id.dev_con);

        bthAdapter=BluetoothAdapter.getDefaultAdapter();

        bthOn.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View view){
                bluetoothOn();
            }
        });

        bthOff.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View view){
                bluetoothOff();
            }
        });

        bthCon.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View view){
                listPairedDevices();
            }
        });

    }

    @Override
    public void onStart(){
        super.onStart();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        if(acceptThread != null){
            acceptThread.cancel();
            acceptThread=null;
        }

        if(connectThread != null){
            connectThread.cancel();
            connectThread=null;
        }


    }

    void bluetoothOn(){
        if(bthAdapter == null){
            Toast.makeText(getApplicationContext(),"블루투스를 지원하지 않는 기기입니다",Toast.LENGTH_SHORT).show();
        }
        else{
            if(bthAdapter.isEnabled()){
                Toast.makeText(getApplicationContext(),"블루투스가 이미 활성화된 상태입니다",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getApplicationContext(),"블루투스가 활성화 되어 있지 않습니다",Toast.LENGTH_SHORT).show();
                Intent intentBthEnable = new Intent(bthAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intentBthEnable,BT_REQUEST_ENABLE);
            }
        }
    }

    void bluetoothOff(){
        if(bthAdapter.isEnabled()){
            bthAdapter.disable();
            Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되었습니다.",Toast.LENGTH_SHORT).show();
            bthStatus.setText("비활성화");
        }
        else{
            Toast.makeText(getApplicationContext(),"블루투스가 이미 비활성화 상태입니다",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        switch(requestCode){
            case BT_REQUEST_ENABLE:
                if(resultCode == RESULT_OK){
                    Toast.makeText(getApplicationContext(),"블루투스 활성화",Toast.LENGTH_LONG).show();
                    bthStatus.setText("활성화");
                    start();
                } else if(resultCode == RESULT_CANCELED){
                    Toast.makeText(getApplicationContext(),"취소",Toast.LENGTH_LONG).show();
                    bthStatus.setText("비활성화");
                }
                break;
        }
        super.onActivityResult(requestCode,resultCode,data);
    }

    void listPairedDevices(){
        if(bthAdapter.isEnabled()){
            pairedDevices = bthAdapter.getBondedDevices();

            if(pairedDevices.size()>0){
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("장치 선택");

                listofPairedDevices = new ArrayList();
                for(BluetoothDevice device: pairedDevices){
                    listofPairedDevices.add(device.getName());
                }
                final CharSequence[] items= listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
                listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);

                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        connectSelectedDevice(items[item].toString());
                    }
                });
                AlertDialog alert=builder.create();
                alert.show();
            }
            else{
                Toast.makeText(getApplicationContext(),"페어링된 장치가 없습니다",Toast.LENGTH_LONG).show();
            }
        }
        else{
            Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되어 있습니다.",Toast.LENGTH_LONG).show();
        }
    }

    void connectSelectedDevice(String selectedDeviceName){
        for(BluetoothDevice tempDevice: pairedDevices){
            if(selectedDeviceName.equals(tempDevice.getName())){
                bthDevice=tempDevice;
                btAddress=bthDevice.getAddress();
                break;
            }
        }
        connect(bthDevice);
        //Toast.makeText(getApplicationContext(),"연결 시도"+bthDevice.getName(),Toast.LENGTH_LONG).show();
    }

    public synchronized void start(){
        acceptThread = new AcceptThread();
        acceptThread.start();
    }

    public synchronized void connect(BluetoothDevice device){
        connectThread=new ConnectThread(device);
        connectThread.start();
    }

    private class AcceptThread extends Thread{
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread(){
            BluetoothServerSocket tmp=null;
            try{
                tmp=bthAdapter.listenUsingRfcommWithServiceRecord("Listen",BT_UUID);
                Toast.makeText(getApplicationContext(),"서버 열림",Toast.LENGTH_LONG).show();
            }catch(IOException e){
                Toast.makeText(getApplicationContext(),"서버 안열림",Toast.LENGTH_LONG).show();
            }
            mmServerSocket=tmp;
        }

        public void run(){
            BluetoothSocket socket=null;
            while(true){
                try{
                    socket=mmServerSocket.accept();
                } catch(IOException e){
                    break;
                }
                if(socket != null){
                    Toast.makeText(getApplicationContext(),"연결됨",Toast.LENGTH_SHORT).show();
                    try{
                        sleep(3000);
                    } catch (Exception e){}
                }
            }
        }

        public void cancel(){
            try{
                mmServerSocket.close();
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    }


    private class ConnectThread extends  Thread{
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device){
            BluetoothSocket tmp=null;
            mmDevice=device;
            try{
                tmp=device.createRfcommSocketToServiceRecord(BT_UUID);
                //Toast.makeText(getApplicationContext(),"클라 초기화 됨.",Toast.LENGTH_LONG).show();
            }catch (IOException e){
                //Toast.makeText(getApplicationContext(),"클라 초기화 실패.",Toast.LENGTH_LONG).show();
            }
            mmSocket=tmp;
            //Toast.makeText(getApplicationContext(),"클라 초기화",Toast.LENGTH_LONG).show();
        }

        public void run() {
            try {
                bthAdapter.cancelDiscovery();
                mmSocket.connect();
                Toast.makeText(getApplicationContext(), "클라이언트 연결", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "연결실패", Toast.LENGTH_LONG).show();
            }
        }

        public void cancel(){
            try{
                mmSocket.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }

}

'''

使用 Android 設備,啟用 BluetoothHCISnoop 日志以了解發生了什么。 它將給出藍牙通信發生的順序流程。 https://www.androidcentral.com/all-about-your-phones-developer-options

可能有以下原因: 1. 在您的代碼中設備地址可能錯誤 2. 您嘗試連接的服務 UUID 應該存在於遠程藍牙設備的服務發現數據庫中 3. 應用程序應該等待連接發生如何以編程方式判斷藍牙設備是否已連接?

暫無
暫無

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

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