<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
本文範例為大家分享了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。
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45