Android學(xué)習(xí)筆記之藍(lán)牙功能_第1頁
Android學(xué)習(xí)筆記之藍(lán)牙功能_第2頁
Android學(xué)習(xí)筆記之藍(lán)牙功能_第3頁
Android學(xué)習(xí)筆記之藍(lán)牙功能_第4頁
Android學(xué)習(xí)筆記之藍(lán)牙功能_第5頁
已閱讀5頁,還剩6頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

第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ù)鏈路層,是一個高層傳輸和應(yīng)用層協(xié)議屏蔽基帶協(xié)議的適配協(xié)議。

1)、第一種打開藍(lán)牙的方式:

IntentenableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableIntent,1);

2)、第二種打開藍(lán)牙方式(靜默)

權(quán)限配置:

uses-permissionandroid:name=”android.permission.BLUETOOTH”/

uses-permissionandroid:name=”android.permission.BLUETOOTH_ADMIN”/

BluetoothAdapteradapter=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。二者需要一個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è)備

importandroid.bluetooth.BluetoothAdapter;

importandroid.bluetooth.BluetoothDevice;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.content.IntentFilter;

importandroid.support.v7.app.AppCompatActivity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.Window;

importandroid.widget.TextView;

importjava.util.Set;

publicclassMainActivityextendsAppCompatActivity{

privateBluetoothAdapterbluetoothAdapter;

privateTextViewtvDevices;

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

setContentView(R.layout.activity_main);

tvDevices=(TextView)findViewById(R.id.tvDevices);

bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

SetBluetoothDevicepaireDevices=bluetoothAdapter.getBondedDevices();

if(paireDevices.size()0){

for(BluetoothDevicedevices:paireDevices){

tvDevices.append(devices.getName()+":"+devices.getAddress());

}

}

IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);//找到一個設(shè)備,發(fā)送一個廣播

this.registerReceiver(receiver,filter);

filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//整個搜索完后發(fā)送廣播

this.registerReceiver(receiver,filter);

}

publicvoidonClick_Search(Viewview){

setProgressBarIndeterminateVisibility(true);

setTitle("正在掃描...");

if(bluetoothAdapter.isDiscovering()){

bluetoothAdapter.cancelDiscovery();

}

bluetoothAdapter.startDiscovery();

}

privatefinalBroadcastReceiverreceiver=newBroadcastReceiver(){

@Override

publicvoidonReceive(Contextcontext,Intentintent){

Stringaction=intent.getAction();

if(BluetoothDevice.ACTION_FOUND.equals(action)){

BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

if(device.getBondState()!=BluetoothDevice.BOND_BONDED){

tvDevices.append(device.getName()+":"+device.getAddress()+"\n");

}

}elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

setProgressBarVisibility(false);

setTitle("搜索完成");

}

}

};

}

真機(jī)測試效果圖:

二、通過搜索,將搜到的設(shè)備連接并實(shí)現(xiàn)傳輸數(shù)據(jù)

importandroid.bluetooth.BluetoothAdapter;

importandroid.bluetooth.BluetoothDevice;

importandroid.bluetooth.BluetoothServerSocket;

importandroid.bluetooth.BluetoothSocket;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.os.Message;

importandroid.support.v7.app.AppCompatActivity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.Window;

importandroid.widget.AdapterView;

importandroid.widget.ArrayAdapter;

importandroid.widget.ListView;

importandroid.widget.Toast;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.Set;

importjava.util.UUID;

publicclassMainActivityextendsAppCompatActivityimplementsAdapterView.OnItemClickListener{

privateBluetoothAdapterbluetoothAdapter;//藍(lán)牙適配器

privateListViewlvDevices;//顯示藍(lán)牙搜索控件

privateListStringbluetoothDevices=newArrayListString//存儲搜索到的所有藍(lán)牙設(shè)備

privateArrayAdapterStringarrayAdapter;

privatefinalUUIDMY_UUID=UUID.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");//手動輸入U(xiǎn)UID碼

privatefinalStringNAME="Bluetooth_Socket";

privateBluetoothSocketclientSocket;//服務(wù)端

privateBluetoothDevicedevice;

privateOutputStreamos;

privateAcceptThreadacceptThread;

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

setContentView(R.layout.activity_main);

bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();//初始化

lvDevices=(ListView)findViewById(R.id.lvDevices);

//顯示配對的藍(lán)牙信息

SetBluetoothDevicepairedDevices=bluetoothAdapter.getBondedDevices();

if(pairedDevices.size()0){

for(BluetoothDevicedevice:pairedDevices){

bluetoothDevices.add(device.getName()+":"+device.getAddress()+"\n");

}

}

//顯示設(shè)備在列表上

arrayAdapter=newArrayAdapterString(this,android.R.layout.simple_list_item_1,

android.R.id.text1,bluetoothDevices);

lvDevices.setAdapter(arrayAdapter);

lvDevices.setOnItemClickListener(this);

acceptThread=newAcceptThread();

acceptThread.start();

}

publicvoidonClick_Search(Viewview){

setProgressBarIndeterminateVisibility(true);

setTitle("正在掃描...");

if(bluetoothAdapter.isDiscovering()){

bluetoothAdapter.cancelDiscovery();

}

bluetoothAdapter.startDiscovery();

}

privatefinalBroadcastReceiverreceiver=newBroadcastReceiver(){

@Override

publicvoidonReceive(Contextcontext,Intentintent){

Stringaction=intent.getAction();

if(BluetoothDevice.ACTION_FOUND.equals(action)){

BluetoothDevicedevice=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");

}

}elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

setProgressBarIndeterminateVisibility(false);

setTitle("連接藍(lán)牙設(shè)備");

}

}

};

/*

*客戶端設(shè)置

*單擊事件

**/

@Override

publicvoidonItemClick(AdapterViewparent,Viewview,intposition,longid){

Strings=arrayAdapter.getItem(position);

Stringaddress=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(IOExceptione){

e.printStackTrace();

}

if(os!=null){

os.write("發(fā)送信息到其他設(shè)備".getBytes("utf-8"));

}

}catch(Exceptione){

e.printStackTrace();

}

}

*服務(wù)端設(shè)置

*設(shè)置一個Handler,用來顯示

privateandroid.os.Handlerhandler=newandroid.os.Handler(){

publicvoidhandleMessage(Messagemsg){

Toast.makeText(MainActivity.this,String.valueOf(msg.obj),Toast.LENGTH_LONG).show();

super.handleMessage(msg);

}

};

//線程類

privateclassAcceptThreadextendsThread{

privateBluetoothServerSocketserverSocket;

privateBluetoothSocketsocket;

privateInput

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論