首頁 > 軟體

Android學習筆記之藍芽功能

2022-09-20 22:02:49

本文範例為大家分享了Android學習筆記之藍芽功能的具體程式碼,供大家參考,具體內容如下

藍芽:短距離無線通訊技術標準。藍芽協定分為4層,即核心協定層、電纜替代協定層、電話控制協定層和其他協定層。其中核心協定層包括基頻、鏈路管理、邏輯鏈路控制和適應協定四部分。鏈路管理(LMP)負責藍芽元件間的建立。邏輯鏈路控制與適應協定(L2CAP)位於基頻協定層上,屬於資料鏈路層,是一個高層傳輸和應用層協定遮蔽基頻協定的適配協定。

1)、第一種開啟藍芽的方式:

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 startActivityForResult(enableIntent,1);

2)、第二種開啟藍芽方式(靜默)

許可權設定:

<uses-permission android:name=」android.permission.BLUETOOTH」/>
  <uses-permission android:name=」android.permission.BLUETOOTH_ADMIN」/>

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();//開啟
adapter.disable();//關閉

3)、通過程式碼搜尋藍芽

藍芽資料傳輸:與Socket類似,網路中使用Socket和ServerSocket控制使用者端和伺服器端,藍芽通訊使用者端為BluetoothSocket,伺服器端為BluetoothServerSocket。二者需要一個UUID(全域性唯一標示符),格式如下:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,被分為5段,其中3段字元數相同,都為4,第1段是8字元,最後一段12字元,UUID相當於Socket的埠,而藍芽地址相當於Socket的IP。

一、搜尋藍芽裝置

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.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.Set;
 
public class MainActivity extends AppCompatActivity {
 
    private BluetoothAdapter bluetoothAdapter;
    private TextView tvDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        tvDevices = (TextView) findViewById(R.id.tvDevices);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> paireDevices = bluetoothAdapter.getBondedDevices();
        if (paireDevices.size()>0){
            for (BluetoothDevice devices:paireDevices){
                tvDevices.append(devices.getName()+":"+devices.getAddress());
            }
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//找到一個裝置,傳送一個廣播
        this.registerReceiver(receiver,filter);
 
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//整個搜尋完後傳送廣播
        this.registerReceiver(receiver,filter);
    }
    public void onClick_Search(View view){
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在掃描...");
        if(bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    tvDevices.append(device.getName() + ":" + device.getAddress() + "n");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarVisibility(false);
                setTitle("搜尋完成");
            }
        }
    };
}

真機測試效果圖:

二、通過搜尋,將搜到的裝置連線並實現傳輸資料

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
 
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private BluetoothAdapter bluetoothAdapter;//藍芽介面卡
    private ListView lvDevices;//顯示藍芽搜尋控制元件
    private List<String> bluetoothDevices = new ArrayList<String>();//儲存搜尋到的所有藍芽裝置
    private ArrayAdapter<String> arrayAdapter;
    private final UUID MY_UUID = UUID.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");//手動輸入UUID碼
    private final String NAME = "Bluetooth_Socket";
    private BluetoothSocket clientSocket;//伺服器端
    private BluetoothDevice device;
    private OutputStream os;
    private AcceptThread acceptThread;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//初始化
        lvDevices = (ListView) findViewById(R.id.lvDevices);
 
     //顯示配對的藍芽資訊
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "n");
            }
        }
        //顯示裝置在列表上
        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                android.R.id.text1, bluetoothDevices);
        lvDevices.setAdapter(arrayAdapter);
        lvDevices.setOnItemClickListener(this);
        acceptThread = new AcceptThread();
        acceptThread.start();
    }
 
    public void onClick_Search(View view) {
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在掃描...");
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }
 
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    bluetoothDevices.add(device.getName()+":"+device.getAddress()+"n");
                    arrayAdapter.notifyDataSetChanged();
//                    tvDevices.append(device.getName() + ":" + device.getAddress() + "n");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle("連線藍芽裝置");
            }
        }
    };
    /*
    * 使用者端設定
    * 單擊事件
    * */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String s = arrayAdapter.getItem(position);
        String address = s.substring(s.indexOf(":") + 1).trim();//獲取藍芽IP
 
        try {
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();//若當前藍芽被使用,則關閉重新啟用
            }
            try {
                if (device == null) {//若未連線,則獲得遠端裝置
                    device = bluetoothAdapter.getRemoteDevice(address);
                }
                if (clientSocket == null) {
                    clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                    clientSocket.connect();//連線藍芽
                    os = clientSocket.getOutputStream();//使用者端向伺服器端輸出文字
 
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (os != null) {
                os.write("傳送資訊到其他裝置".getBytes("utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/*
* 伺服器端設定
* 設定一個Handler,用來顯示
* */
    private android.os.Handler handler = new android.os.Handler() {
        public void handleMessage(Message msg) {
            Toast.makeText(MainActivity.this, String.valueOf(msg.obj), Toast.LENGTH_LONG).show();
            super.handleMessage(msg);
        }
    };
    //執行緒類
    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        private BluetoothSocket socket;
        private InputStream is;
        private OutputStream os;
 
        public AcceptThread() {
            try {
                serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        public void run() {
            try {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                os = socket.getOutputStream();
                while (true) {
                    byte[] buffer = new byte[128];
                    int count = is.read(buffer);
                    Message msg = new Message();
                    msg.obj = new String(buffer, 0, count, "utf-8");
                    handler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

真機測試效果圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com