Android開發中編寫藍芽相關功能的核心代碼講解_Android

來源:互聯網
上載者:User

一. 什麼是藍芽(Bluetooth)?
1.1  BuleTooth是目前使用最廣泛的無線通訊協議
1.2  主要針對短距離裝置通訊(10m)
1.3  常用於串連耳機,滑鼠和移動通訊裝置等.
二. 與藍芽相關的API
2.1 BluetoothAdapter:
代表了本地的藍芽適配器
2.2 BluetoothDevice
代表了一個遠端Bluetooth裝置
三. 掃描已經配對的藍牙裝置(1)
註:必須部署在真實手機上,模擬器無法實現
首先需要在AndroidManifest.xml 聲明藍芽許可權
<user-permission android:name="android.permission.BLUETOOTH" />
配對藍芽需要手動操作:
1. 開啟設定--> 無線網路 --> 藍芽 勾選開啟
2. 開啟藍芽設定  掃描周圍已經開啟的藍牙裝置(可以與自己的膝上型電腦進行配對),點擊進行配對
 電腦上會彈出提示視窗: 添加裝置
 顯示計算與裝置之間的配對碼,要求確認是否配對
 手機上也會顯示類似的提示.
四. 掃描已經配對的藍牙裝置(2)
4.1 獲得BluetoothAdapter對象
4.2 判斷當前行動裝置中是否擁有藍芽
4.3 判斷當前行動裝置中藍芽是否已經開啟
4.4 得到所有已經配對的藍牙裝置對象


藍芽配對實現的核心代碼如下:

MainActivity:import java.util.Iterator; import java.util.Set;  import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;  public class MainActivity extends Activity {   private Button button = null;   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);          button = (Button)findViewById(R.id.buttonId);     button.setOnClickListener(new OnClickListener(){        @Override       public void onClick(View v) {         //獲得BluetoothAdapter對象,該API是android 2.0開始支援的         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();         //adapter不等於null,說明本機有藍牙裝置         if(adapter != null){           System.out.println("本機有藍牙裝置!");           //如果藍牙裝置未開啟           if(!adapter.isEnabled()){             Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);             //請求開啟藍牙裝置             startActivity(intent);           }           //獲得已配對的遠程藍牙裝置的集合           Set<BluetoothDevice> devices = adapter.getBondedDevices();           if(devices.size()>0){             for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){               BluetoothDevice device = (BluetoothDevice)it.next();               //列印出遠程藍牙裝置的物理地址               System.out.println(device.getAddress());             }           }else{             System.out.println("還沒有已配對的遠程藍牙裝置!");           }         }else{           System.out.println("本機沒有藍牙裝置!");         }       }     });   } } 


修改本機藍牙裝置的可見度,並掃描周圍可用的藍牙裝置
1. 修改本機藍牙裝置的可見度
2. 掃描周圍可用的藍牙裝置

Eg:
一.  資訊清單檔AdroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.se7en"    android:versionCode="1"    android:versionName="1.0">   <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">     <activity android:name=".MainActivity"          android:label="@string/app_name">       <intent-filter>         <action android:name="android.intent.action.MAIN" />         <category android:name="android.intent.category.LAUNCHER" />       </intent-filter>     </activity>   </application>   <uses-permission android:name="android.permission.BLUETOOTH"/>      <!-若需要管理藍牙裝置,如修改可見度,則需以下的許可權->   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> </manifest> 

二. 布局檔案: main.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:orientation="vertical"   android:layout_width="fill_parent"   android:layout_height="fill_parent"   >   <TextView      android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:text="@string/hello"     />   <Button      android:id="@+id/discoverButton"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="設定可見度"/>   <Button      android:id="@+id/scanButton"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="開始掃描"/> </LinearLayout> 

三. MainActivity:

import android.app.Activity; 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.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;  public class MainActivity extends Activity {   private Button discoverButton = null;   private Button scanButton = null;   private BluetoothAdapter adapter = null;   private BluetoothReceiver bluetoothReceiver = null;   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);          adapter = BluetoothAdapter.getDefaultAdapter();          discoverButton = (Button)findViewById(R.id.discoverButton);     scanButton = (Button)findViewById(R.id.scanButton);     //修改藍牙裝置的可見度     discoverButton.setOnClickListener(new OnClickListener(){       @Override       public void onClick(View view) {       Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  //設定藍芽可見度,500表示可見時間(單位:秒),當值大於300時預設為300 discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500); startActivity(discoverIntent);       }     });          scanButton.setOnClickListener(new OnClickListener(){       @Override       public void onClick(View v) {     //開始掃描周圍藍牙裝置,該方法是非同步呼叫並以廣播的機制返回,所以需要建立一個BroadcastReceiver來擷取資訊         adapter.startDiscovery();       }     });          //設定廣播接收的filter     IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);     //建立藍芽廣播資訊的receiver     bluetoothReceiver = new BluetoothReceiver ();     //註冊廣播接收器     registerReceiver(bluetoothReceiver,intentFilter);          }      private class BluetoothReceiver extends BroadcastReceiver{     @Override     public void onReceive(Context context, Intent intent) {       //獲得掃描到的遠程藍牙裝置       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);       System.out.println(device.getAddress());     }        } } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.