源代码:

main.xml:

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"android:orientation="vertical">
  5. <TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:text="TextView"android:layout_height="wrap_content"></TextView>
  6. <LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/linearLayout1">
  7. <Buttonandroid:id="@+id/button1"android:text="OFF"android:layout_width="wrap_content"android:layout_height="wrap_content"></Button>
  8. </LinearLayout>
  9. <LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/linearLayout2">
  10. <Buttonandroid:id="@+id/button2"android:text="开启可见"android:layout_width="wrap_content"android:layout_height="wrap_content"></Button>
  11. <TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="设备不可见"></TextView>
  12. </LinearLayout>
  13. <LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/linearLayout3">
  14. <Buttonandroid:id="@+id/button3"android:text="扫描:OFF"android:layout_width="wrap_content"android:layout_height="wrap_content"></Button>
  15. <TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="停止扫描"></TextView>
  16. </LinearLayout>
  17. <ListViewandroid:id="@+id/listView1"android:layout_height="wrap_content"android:layout_width="match_parent"></ListView>
  18. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:text="TextView" android:layout_height="wrap_content"></TextView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1"> <Button android:id="@+id/button1" android:text="OFF" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2"> <Button android:id="@+id/button2" android:text="开启可见 " android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设备不可见 "></TextView> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3"> <Button android:id="@+id/button3" android:text="扫描:OFF" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止扫描 "></TextView> </LinearLayout> <ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView> </LinearLayout>
test_bluetooth.java:

[java] view plain copy print ?
  1. packagecom.test_bluetooth;
  2. importjava.util.Set;
  3. importandroid.app.Activity;
  4. importandroid.bluetooth.BluetoothAdapter;
  5. importandroid.bluetooth.BluetoothDevice;
  6. importandroid.content.BroadcastReceiver;
  7. importandroid.content.Context;
  8. importandroid.content.Intent;
  9. importandroid.content.IntentFilter;
  10. importandroid.os.Bundle;
  11. importandroid.os.CountDownTimer;
  12. importandroid.view.View;
  13. importandroid.widget.ArrayAdapter;
  14. importandroid.widget.Button;
  15. importandroid.widget.ListView;
  16. importandroid.widget.TextView;
  17. publicclasstest_bluetoothextendsActivityimplementsView.OnClickListener
  18. {
  19. privatestaticfinalintREQUEST_ENABLE_BT=2;
  20. TextViewtxt;
  21. TextViewtxt_see;
  22. TextViewtxt_scan;
  23. BluetoothAdaptermBluetoothAdapter;
  24. ArrayAdapter<String>mArrayAdapter;
  25. Buttonbtn_switch;
  26. Buttonbtn_see;
  27. Buttonbtn_scan;
  28. ListViewlist;
  29. CountDownTimersee_timer;
  30. CountDownTimerscan_timer;
  31. /**Calledwhentheactivityisfirstcreated.*/
  32. @Override
  33. publicvoidonCreate(BundlesavedInstanceState)
  34. {
  35. super.onCreate(savedInstanceState);
  36. setContentView(R.layout.main);
  37. txt=(TextView)findViewById(R.id.textView1);
  38. txt_see=(TextView)findViewById(R.id.textView2);
  39. txt_scan=(TextView)findViewById(R.id.textView3);
  40. //绑定XML中的ListView,作为Item的容器
  41. list=(ListView)findViewById(R.id.listView1);
  42. //获取蓝牙适配器
  43. mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
  44. mArrayAdapter=newArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
  45. if(mBluetoothAdapter==null)
  46. {
  47. //DevicedoesnotsupportBluetooth
  48. txt.setText("fail");
  49. //退出程序
  50. test_bluetooth.this.finish();
  51. }
  52. btn_switch=(Button)findViewById(R.id.button1);
  53. btn_switch.setOnClickListener(this);
  54. btn_see=(Button)findViewById(R.id.button2);
  55. btn_see.setOnClickListener(this);
  56. btn_see.setEnabled(false);
  57. btn_scan=(Button)findViewById(R.id.button3);
  58. btn_scan.setOnClickListener(this);
  59. btn_scan.setText("扫描:OFF");
  60. btn_scan.setEnabled(false);
  61. //判断蓝牙是否已经被打开
  62. if(mBluetoothAdapter.isEnabled())
  63. {
  64. //打开
  65. btn_switch.setText("ON");
  66. btn_see.setEnabled(true);
  67. btn_scan.setEnabled(true);
  68. }
  69. see_timer=newCountDownTimer(120000,1000)
  70. {
  71. @Override
  72. publicvoidonTick(longmillisUntilFinished)
  73. {
  74. txt_see.setText("剩余可见时间"+millisUntilFinished/1000+"秒");
  75. }
  76. @Override
  77. publicvoidonFinish()
  78. {
  79. //判断蓝牙是否已经被打开
  80. if(mBluetoothAdapter.isEnabled())
  81. {
  82. btn_see.setEnabled(true);
  83. txt_see.setText("设备不可见");
  84. }
  85. }
  86. };
  87. scan_timer=newCountDownTimer(12000,1000)
  88. {
  89. @Override
  90. publicvoidonTick(longmillisUntilFinished)
  91. {
  92. txt_scan.setText("剩余扫描时间"+millisUntilFinished/1000+"秒");
  93. }
  94. @Override
  95. publicvoidonFinish()
  96. {
  97. //判断蓝牙是否已经被打开
  98. if(mBluetoothAdapter.isEnabled())
  99. {
  100. btn_scan.setEnabled(true);
  101. //关闭扫描
  102. mBluetoothAdapter.cancelDiscovery();
  103. btn_scan.setText("扫描:OFF");
  104. txt_scan.setText("停止扫描");
  105. }
  106. }
  107. };
  108. }
  109. @Override
  110. protectedvoidonDestroy(){
  111. super.onDestroy();
  112. android.os.Process.killProcess(android.os.Process.myPid());
  113. }
  114. @Override
  115. publicvoidonClick(Viewv)
  116. {
  117. //TODOAuto-generatedmethodstub
  118. switch(v.getId())
  119. {
  120. caseR.id.button1:
  121. {
  122. Stringstr=btn_switch.getText().toString();
  123. if(str=="OFF")
  124. {
  125. if(!mBluetoothAdapter.isEnabled())
  126. {
  127. //打开蓝牙
  128. IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  129. startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
  130. txt.setText("s1");
  131. btn_see.setEnabled(true);
  132. btn_scan.setText("扫描:OFF");
  133. btn_scan.setEnabled(true);
  134. }
  135. }
  136. else
  137. {
  138. //关闭蓝牙
  139. mBluetoothAdapter.disable();
  140. btn_switch.setText("OFF");
  141. mArrayAdapter.clear();
  142. list.setAdapter(mArrayAdapter);
  143. btn_see.setEnabled(false);
  144. btn_scan.setEnabled(false);
  145. }
  146. break;
  147. }
  148. caseR.id.button2:
  149. {
  150. //开启可见
  151. IntentenableBtIntent_See=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  152. startActivityForResult(enableBtIntent_See,3);
  153. txt.setText("s1");
  154. btn_see.setEnabled(false);
  155. see_timer.start();
  156. break;
  157. }
  158. caseR.id.button3:
  159. {
  160. Stringstr=btn_scan.getText().toString();
  161. if(str=="扫描:OFF")
  162. {
  163. txt.setText("s5");
  164. if(mBluetoothAdapter.isEnabled())
  165. {
  166. //开始扫描
  167. mBluetoothAdapter.startDiscovery();
  168. txt.setText("s6");
  169. btn_scan.setText("扫描:ON");
  170. //CreateaBroadcastReceiverforACTION_FOUND
  171. finalBroadcastReceivermReceiver=newBroadcastReceiver()
  172. {
  173. @Override
  174. publicvoidonReceive(Contextcontext,Intentintent)
  175. {
  176. //TODOAuto-generatedmethodstub
  177. Stringaction=intent.getAction();
  178. //Whendiscoveryfindsadevice
  179. mArrayAdapter.clear();
  180. if(BluetoothDevice.ACTION_FOUND.equals(action))
  181. {
  182. //GettheBluetoothDeviceobjectfromtheIntent
  183. BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  184. //AddthenameandaddresstoanarrayadaptertoshowinaListView
  185. mArrayAdapter.add(device.getName()+":"+device.getAddress());
  186. }
  187. list.setAdapter(mArrayAdapter);
  188. }
  189. };
  190. //RegistertheBroadcastReceiver
  191. IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
  192. registerReceiver(mReceiver,filter);//Don'tforgettounregisterduringonDestroy
  193. scan_timer.start();
  194. }
  195. }
  196. else
  197. {
  198. //关闭扫描
  199. mBluetoothAdapter.cancelDiscovery();
  200. btn_scan.setText("扫描:OFF");
  201. scan_timer.cancel();
  202. txt_scan.setText("停止扫描");
  203. }
  204. break;
  205. }
  206. default:
  207. break;
  208. }
  209. }
  210. publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata)
  211. {
  212. switch(requestCode)
  213. {
  214. caseREQUEST_ENABLE_BT:
  215. //WhentherequesttoenableBluetoothreturns
  216. if(resultCode==Activity.RESULT_OK)
  217. {
  218. //Bluetoothisnowenabled,sosetupachatsession
  219. btn_switch.setText("ON");
  220. txt.setText("s4");
  221. //获取蓝牙列表
  222. Set<BluetoothDevice>pairedDevices=mBluetoothAdapter.getBondedDevices();
  223. mArrayAdapter.clear();
  224. //Iftherearepaireddevices
  225. if(pairedDevices.size()>0)
  226. {
  227. //txt.setText("s3");
  228. //Loopthroughpaireddevices
  229. for(BluetoothDevicedevice:pairedDevices)
  230. {
  231. //AddthenameandaddresstoanarrayadaptertoshowinaListView
  232. mArrayAdapter.add(device.getName()+":"+device.getAddress());
  233. }
  234. list.setAdapter(mArrayAdapter);
  235. }
  236. }else
  237. {
  238. finish();
  239. }
  240. }
  241. }
  242. }
package com.test_bluetooth; import java.util.Set; 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.os.CountDownTimer; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class test_bluetooth extends Activity implements View.OnClickListener { private static final int REQUEST_ENABLE_BT = 2; TextView txt; TextView txt_see; TextView txt_scan; BluetoothAdapter mBluetoothAdapter; ArrayAdapter<String> mArrayAdapter; Button btn_switch; Button btn_see; Button btn_scan; ListView list; CountDownTimer see_timer; CountDownTimer scan_timer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txt = (TextView)findViewById(R.id.textView1); txt_see = (TextView)findViewById(R.id.textView2); txt_scan = (TextView)findViewById(R.id.textView3); //绑定XML中的ListView,作为Item的容器 list = (ListView) findViewById(R.id.listView1); //获取蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1); if (mBluetoothAdapter == null) { // Device does not support Bluetooth txt.setText("fail"); //退出程序 test_bluetooth.this.finish(); } btn_switch = (Button)findViewById(R.id.button1); btn_switch.setOnClickListener(this); btn_see = (Button)findViewById(R.id.button2); btn_see.setOnClickListener(this); btn_see.setEnabled(false); btn_scan = (Button)findViewById(R.id.button3); btn_scan.setOnClickListener(this); btn_scan.setText("扫描:OFF"); btn_scan.setEnabled(false); //判断蓝牙是否已经被打开 if (mBluetoothAdapter.isEnabled()) { //打开 btn_switch.setText("ON"); btn_see.setEnabled(true); btn_scan.setEnabled(true); } see_timer = new CountDownTimer(120000,1000) { @Override public void onTick( long millisUntilFinished) { txt_see.setText( "剩余可见时间" + millisUntilFinished / 1000 + "秒"); } @Override public void onFinish() { //判断蓝牙是否已经被打开 if (mBluetoothAdapter.isEnabled()) { btn_see.setEnabled(true); txt_see.setText( "设备不可见"); } } }; scan_timer = new CountDownTimer(12000,1000) { @Override public void onTick( long millisUntilFinished) { txt_scan.setText( "剩余扫描时间" + millisUntilFinished / 1000 + "秒"); } @Override public void onFinish() { //判断蓝牙是否已经被打开 if (mBluetoothAdapter.isEnabled()) { btn_scan.setEnabled(true); //关闭扫描 mBluetoothAdapter.cancelDiscovery(); btn_scan.setText("扫描:OFF"); txt_scan.setText( "停止扫描"); } } }; } @Override protected void onDestroy() { super.onDestroy(); android.os.Process.killProcess(android.os.Process.myPid()); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: { String str = btn_switch.getText().toString(); if (str == "OFF") { if (!mBluetoothAdapter.isEnabled()) { //打开蓝牙 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); txt.setText("s1"); btn_see.setEnabled(true); btn_scan.setText("扫描:OFF"); btn_scan.setEnabled(true); } } else { //关闭蓝牙 mBluetoothAdapter.disable(); btn_switch.setText("OFF"); mArrayAdapter.clear(); list.setAdapter(mArrayAdapter); btn_see.setEnabled(false); btn_scan.setEnabled(false); } break; } case R.id.button2: { //开启可见 Intent enableBtIntent_See = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(enableBtIntent_See, 3); txt.setText("s1"); btn_see.setEnabled(false); see_timer.start(); break; } case R.id.button3: { String str = btn_scan.getText().toString(); if (str == "扫描:OFF") { txt.setText("s5"); if (mBluetoothAdapter.isEnabled()) { //开始扫描 mBluetoothAdapter.startDiscovery(); txt.setText("s6"); btn_scan.setText("扫描:ON"); // Create a BroadcastReceiver for ACTION_FOUND final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); // When discovery finds a device mArrayAdapter.clear(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + ":" + device.getAddress()); } list.setAdapter(mArrayAdapter); } }; // Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy scan_timer.start(); } } else { //关闭扫描 mBluetoothAdapter.cancelDiscovery(); btn_scan.setText("扫描:OFF"); scan_timer.cancel(); txt_scan.setText( "停止扫描"); } break; } default: break; } } public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { // Bluetooth is now enabled, so set up a chat session btn_switch.setText("ON"); txt.setText("s4"); //获取蓝牙列表 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); mArrayAdapter.clear(); // If there are paired devices if (pairedDevices.size() > 0) { //txt.setText("s3"); // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + ":" + device.getAddress()); } list.setAdapter(mArrayAdapter); } } else { finish(); } } } }效果图:

Android:BT测试代码_第1张图片

更多相关文章

  1. Android TimeLine 时间节点轴的实现
  2. Android时间工具类 本地转UTC,UTC转本地
  3. 安卓4.X系统 增加蓝牙接收文件类型
  4. 【Android】Android蓝牙开发深入解析
  5. android 传统蓝牙开发 (附示例源码)
  6. android:sharedUserId="android.uid.system" 使用系统签名+SNTP
  7. Android ----蓝牙架构
  8. Android中日期和时间控件的使用

随机推荐

  1. android6.0 系统时间不自动校准的问题
  2. Android(安卓)Camera CameraHal.cpp 分析
  3. Android之RecyclerView的局部刷新
  4. {Android} 测试Google Play In-App-Billi
  5. 四大组件之Service_AIDL
  6. Android适配器
  7. Android(安卓)应用程序中的界面控件与程
  8. android屏蔽listview 的item事件
  9. 编写在Android的Linux系统中直接运行的可
  10. 【Android】编程规范与常用技巧