Android開發之藍芽操作

來源:互聯網
上載者:User

Android開發之藍芽操作
藍芽操作
一、什麼是藍芽
1、Bluetooth廣泛使用的一種無線通訊協議
2、主要針對短距離通訊(10m)
3、常用於耳機、滑鼠、鍵盤等移動通訊裝置
二、與藍芽相關的API
1、BluetoothAdapter:代表本地藍牙裝置
2、BluetoothDevice:代表遠程藍牙裝置
三、藍芽需要的設定
需要在AndroidManifest中申明藍芽操作的許可權
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
四、掃描已經配對的藍牙裝置
1、擷取BluetoothAdapter對象
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter()
2、判斷當前裝置中是否有藍牙裝置
if(adapter != null){}
3、判斷當前裝置中的藍牙裝置是否已經開啟
使用adapter.isEnabled()方法
4、得到所有已經配對的藍牙裝置
Set<BluetoothDevice> devices = adapter.getBondedDevices();
五、設定藍牙裝置的可見度
1、建立intent對象:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
2、設定可見度的時間,最大300s,超過300s系統會自動設為300s
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
3、啟動Android內建activity,將參數傳入
startActivity(discoverableIntent);
六、掃描周圍可見的藍芽
1、調用startDiscovery()來掃描周圍可見裝置
BluetoothAdapter.getDefaultAdapter().startDiscovery();
2、每次掃描到系統就會發送廣播
A、建立一個過濾器,過濾廣播ACTION_FOUND
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
B、建立一個廣播接收器
BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
C、 註冊接收器
registerReceiver(bluetoothReceiver, intentFilter);
D、在廣播中取出資料
String action = intent.getAction();
//從intent取出遠程藍牙裝置
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
七、原始碼
MainActivity.java

  1. package com.example.bluetooth;

  2. import java.util.Iterator;
  3. import java.util.Set;

  4. import android.os.Bundle;
  5. import android.app.Activity;
  6. import android.app.SearchManager.OnCancelListener;
  7. import android.bluetooth.BluetoothAdapter;
  8. import android.bluetooth.BluetoothDevice;
  9. import android.content.BroadcastReceiver;
  10. import android.content.Context;
  11. import android.content.DialogInterface;
  12. import android.content.IntentFilter;
  13. import android.content.DialogInterface.OnClickListener;
  14. import android.content.Intent;
  15. import android.view.Menu;
  16. import android.view.View;
  17. import android.webkit.WebView.FindListener;
  18. import android.widget.Button;
  19. import android.widget.EditText;

  20. public class MainActivity extends Activity
  21. {

  22. private Button findBtn = null;
  23. private Button scanBtn = null;
  24. private Button setBtn = null;
  25. private EditText edit1 = null;

  26. @Override
  27. protected void onCreate(Bundle savedInstanceState)
  28. {
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.activity_main);
  31. //找到按鈕
  32. findBtn = (Button)findViewById(R.id.findBtn);
  33. scanBtn = (Button)findViewById(R.id.scanBtn);
  34. setBtn = (Button)findViewById(R.id.setBtn);
  35. //設定監聽器
  36. findBtn.setOnClickListener(new btnOnclickListener());
  37. scanBtn.setOnClickListener(new btnOnclickListener());
  38. setBtn.setOnClickListener(new btnOnclickListener());

  39. edit1 = (EditText)findViewById(R.id.edit1);
  40. //建立一個過濾器,過濾廣播ACTION_FOUND
  41. IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  42. //建立一個廣播接收器
  43. BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
  44. //註冊接收器
  45. registerReceiver(bluetoothReceiver, intentFilter);
  46. }

  47. class btnOnclickListener implements android.view.View.OnClickListener
  48. {

  49. @Override
  50. public void onClick(View v)
  51. {
  52. // TODO Auto-generated method stub
  53. switch(v.getId())
  54. {
  55. case R.id.findBtn:
  56. //擷取BluetoothAdapter對象
  57. BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  58. //如果得到了裝置
  59. if(adapter != null)
  60. {
  61. //更新edittext,列印有裝置
  62. edit1.append("have!"+'\n');
  63. //如果裝置沒有被開啟
  64. if(!adapter.isEnabled())
  65. {
  66. //啟動新的activity,開啟藍芽
  67. Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  68. startActivity(intent);
  69. }
  70. //擷取所有已經配對的藍芽,得到一個藍牙裝置集
  71. Set<BluetoothDevice> devices = adapter.getBondedDevices();
  72. if(devices.size()>0)
  73. {
  74. //如果有已經配對的藍芽,那麼用迭代逐個列印出來
  75. for(Iterator iterator=devices.iterator(); iterator.hasNext();)
  76. {
  77. BluetoothDevice bluetoothDevice = (BluetoothDevice)iterator.next();
  78. edit1.append(bluetoothDevice.getAddress()+'\n');
  79. }
  80. }
  81. }
  82. else
  83. {
  84. edit1.append("no device!!");
  85. }
  86. break;
  87. case R.id.scanBtn:
  88. //調用startDiscovery()來掃描周圍可見裝置
  89. BluetoothAdapter.getDefaultAdapter().startDiscovery();
  90. break;
  91. case R.id.setBtn:
  92. //建立intent通過intent傳遞參數
  93. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  94. //設定可見狀態的期間,如果超過300s,那麼系統會自動設為300s
  95. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  96. //啟動activity,這是Android內建的
  97. startActivity(discoverableIntent);
  98. break;
  99. default:
  100. break;
  101. }

  102. }
  103. }

  104. private class BluetoothReceiver extends BroadcastReceiver
  105. {

  106. @Override
  107. public void onReceive(Context context, Intent intent)
  108. {
  109. // TODO Auto-generated method stub
  110. //接受intent
  111. String action = intent.getAction();
  112. //從intent取出遠程藍牙裝置
  113. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  114. edit1.append("find new device:"+device.getAddress()+"\n");
  115. }

  116. }
  117. @Override
  118. public boolean onCreateOptionsMenu(Menu menu)
  119. {
  120. // Inflate the menu; this adds items to the action bar if it is present.
  121. getMenuInflater().inflate(R.menu.main, menu);
  122. return true;
  123. }

  124. }
布局檔案
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity" >

  10. <Button
  11. android:id="@+id/findBtn"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:text="掃描已經串連的藍芽"
  15. />
  16. <Button
  17. android:id="@+id/setBtn"
  18. android:layout_width="fill_parent"
  19. android:layout_height="wrap_content"
  20. android:layout_below="@+id/findBtn"
  21. android:text="設定藍芽可見度"
  22. />
  23. <Button
  24. android:id="@+id/scanBtn"
  25. android:layout_width="fill_parent"
  26. android:layout_height="wrap_content"
  27. android:layout_below="@+id/setBtn"
  28. android:text="掃描周圍可見的藍芽"
  29. />
  30. <EditText
  31. android:id="@+id/edit1"
  32. android:layout_width="fill_parent"
  33. android:layout_height="wrap_content"
  34. android:layout_below="@+id/scanBtn"
  35. />

  36. </RelativeLayout>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.