Android學(xué)習(xí)筆記之藍(lán)牙功能
本文實(shí)例為大家分享了Android學(xué)習(xí)筆記之藍(lán)牙功能的具體代碼,供大家參考,具體內(nèi)容如下
藍(lán)牙:短距離無線通訊技術(shù)標(biāo)準(zhǔn)。藍(lán)牙協(xié)議分為4層,即核心協(xié)議層、電纜替代協(xié)議層、電話控制協(xié)議層和其他協(xié)議層。其中核心協(xié)議層包括基帶、鏈路管理、邏輯鏈路控制和適應(yīng)協(xié)議四部分。鏈路管理(LMP)負(fù)責(zé)藍(lán)牙組件間的建立。邏輯鏈路控制與適應(yīng)協(xié)議(L2CAP)位于基帶協(xié)議層上,屬于數(shù)據(jù)鏈路層,是一個(gè)高層傳輸和應(yīng)用層協(xié)議屏蔽基帶協(xié)議的適配協(xié)議。
1)、第一種打開藍(lán)牙的方式:
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); ?startActivityForResult(enableIntent,1);
2)、第二種打開藍(lán)牙方式(靜默)
權(quán)限配置:
<uses-permission android:name=”android.permission.BLUETOOTH”/> ? <uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/> BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); adapter.enable();//打開 adapter.disable();//關(guān)閉
3)、通過代碼搜索藍(lán)牙
藍(lán)牙數(shù)據(jù)傳輸:與Socket類似,網(wǎng)絡(luò)中使用Socket和ServerSocket控制客戶端和服務(wù)端,藍(lán)牙通訊客戶端為BluetoothSocket,服務(wù)端為BluetoothServerSocket。二者需要一個(gè)UUID(全局唯一標(biāo)示符),格式如下:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,被分為5段,其中3段字符數(shù)相同,都為4,第1段是8字符,最后一段12字符,UUID相當(dāng)于Socket的端口,而藍(lán)牙地址相當(dāng)于Socket的IP。
一、搜索藍(lán)牙設(shè)備
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);//找到一個(gè)設(shè)備,發(fā)送一個(gè)廣播 ? ? ? ? this.registerReceiver(receiver,filter); ? ? ? ? ? filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//整個(gè)搜索完后發(fā)送廣播 ? ? ? ? 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("搜索完成"); ? ? ? ? ? ? } ? ? ? ? } ? ? }; }
真機(jī)測(cè)試效果圖:
二、通過搜索,將搜到的設(shè)備連接并實(shí)現(xiàn)傳輸數(shù)據(jù)
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;//藍(lán)牙適配器 ? ? private ListView lvDevices;//顯示藍(lán)牙搜索控件 ? ? private List<String> bluetoothDevices = new ArrayList<String>();//存儲(chǔ)搜索到的所有藍(lán)牙設(shè)備 ? ? private ArrayAdapter<String> arrayAdapter; ? ? private final UUID MY_UUID = UUID.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");//手動(dòng)輸入U(xiǎn)UID碼 ? ? private final String NAME = "Bluetooth_Socket"; ? ? private BluetoothSocket clientSocket;//服務(wù)端 ? ? 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); ? ??? ?//顯示配對(duì)的藍(lán)牙信息 ? ? ? ? Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); ? ? ? ? if (pairedDevices.size() > 0) { ? ? ? ? ? ? for (BluetoothDevice device : pairedDevices) { ? ? ? ? ? ? ? ? bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "\n"); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? //顯示設(shè)備在列表上 ? ? ? ? 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("連接藍(lán)牙設(shè)備"); ? ? ? ? ? ? } ? ? ? ? } ? ? }; ? ? /* ? ? * 客戶端設(shè)置 ? ? * 單擊事件 ? ? * */ ? ? @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();//獲取藍(lán)牙IP ? ? ? ? ? try { ? ? ? ? ? ? if (bluetoothAdapter.isDiscovering()) { ? ? ? ? ? ? ? ? bluetoothAdapter.cancelDiscovery();//若當(dāng)前藍(lán)牙被使用,則關(guān)閉重新啟用 ? ? ? ? ? ? } ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? if (device == null) {//若未連接,則獲得遠(yuǎn)程設(shè)備 ? ? ? ? ? ? ? ? ? ? device = bluetoothAdapter.getRemoteDevice(address); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? if (clientSocket == null) { ? ? ? ? ? ? ? ? ? ? clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID); ? ? ? ? ? ? ? ? ? ? clientSocket.connect();//連接藍(lán)牙 ? ? ? ? ? ? ? ? ? ? os = clientSocket.getOutputStream();//客戶端向服務(wù)端輸出文本 ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } catch (IOException e) { ? ? ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? ? ? } ? ? ? ? ? ? if (os != null) { ? ? ? ? ? ? ? ? os.write("發(fā)送信息到其他設(shè)備".getBytes("utf-8")); ? ? ? ? ? ? } ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } /* * 服務(wù)端設(shè)置 * 設(shè)置一個(gè)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(); ? ? ? ? ? ? } ? ? ? ? } ? ? } }
真機(jī)測(cè)試效果圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android有效獲取狀態(tài)欄(StatusBar)高度的方法
這篇文章主要介紹了Android有效獲取狀態(tài)欄(StatusBar)高度的方法,涉及Android針對(duì)狀態(tài)欄(StatusBar)屬性操作的相關(guān)技巧,需要的朋友可以參考下2016-08-08android網(wǎng)絡(luò)編程之a(chǎn)ndroid連接網(wǎng)絡(luò)的簡(jiǎn)單示例代碼
這篇文章主要介紹了android連接網(wǎng)絡(luò)的簡(jiǎn)單示例,需要的朋友可以參考下2014-04-04Android實(shí)現(xiàn)IM多人員組合的群組頭像
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)IM多人員組合的群組頭像,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10Android啟動(dòng)內(nèi)置APK和動(dòng)態(tài)發(fā)送接收自定義廣播實(shí)例詳解
這篇文章主要介紹了Android啟動(dòng)內(nèi)置APK和動(dòng)態(tài)發(fā)送接收自定義廣播實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06Android之scrollview滑動(dòng)使標(biāo)題欄漸變背景色的實(shí)例代碼
這篇文章主要介紹了Android之scrollview滑動(dòng)使標(biāo)題欄漸變背景色的實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05android 線性布局LinearLayout實(shí)例代碼
android 線性布局LinearLayout實(shí)例代碼,需要的朋友可以參考一下2013-05-05Android仿QQ未讀消息--紅點(diǎn)拖拽刪除【源代碼】
本文Demo是一款仿qq未讀消息拖拽刪除的例子,繼承RelativeLayout的WaterDrop實(shí)現(xiàn)了圓形圖標(biāo)功能;繼承ImageView的CircleImageView圓形圖片功能。效果非常不錯(cuò),很適合有圓形設(shè)計(jì)的朋友參考2017-04-04android開發(fā)設(shè)計(jì)模式之——單例模式詳解
本篇文章主要介紹了android開發(fā)設(shè)計(jì)模式之——單例模式詳解,具有一定的參考價(jià)值,有需要的可以了解一下。2016-11-11