新建一个工程“blt”。

-----------------------MainActivity.java

packagecom.example.blt;importjava.io.IOException;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;importjava.util.Set;importjava.util.UUID;importandroid.annotation.SuppressLint;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.app.ProgressDialog;importandroid.bluetooth.BluetoothAdapter;importandroid.bluetooth.BluetoothDevice;importandroid.bluetooth.BluetoothSocket;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.util.Log;importandroid.view.KeyEvent;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.widget.AdapterView;importandroid.widget.AdapterView.OnItemClickListener;importandroid.widget.ArrayAdapter;importandroid.widget.ListView;importandroid.widget.Toast;publicclassMainActivityextendsActivity{staticfinalStringSPP_UUID="00001101-0000-1000-8000-00805F9B34FB";//适配器privateBluetoothAdapterblueadapter=null;//设备地址列表privateList<String>deviceList=newArrayList<String>();privateArrayAdapter<String>adapter;privateListViewdeviceListview;privatebooleanisFind=false;//存储设备信息privateList<UserDriver>userDrivers=newArrayList<UserDriver>();//连接设备publicstaticBluetoothSocketbtSocket;intuseIndex;ProgressDialogpDialog;privatelongexitTime=0;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){pDialog=newProgressDialog(MainActivity.this);super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setView();setBluetooth();}//设置列表信息privatevoidsetView(){adapter=newArrayAdapter<String>(this,android.R.layout.simple_list_item_1,deviceList);deviceListview=(ListView)findViewById(R.id.listView1);deviceListview.setAdapter(adapter);deviceListview.setOnItemClickListener(newOnItemClickListener(){@OverridepublicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){useIndex=position;//TODOAuto-generatedmethodstubnewAlertDialog.Builder(MainActivity.this).setTitle("提示框").setMessage("确认连接?"+userDrivers.get(useIndex).DeviceAdapter.getName()).setPositiveButton("确定",newDialogInterface.OnClickListener(){publicvoidonClick(DialogInterfacedialog,intwhich){//判断是否需要配对switch(userDrivers.get(useIndex).DeviceAdapter.getBondState()){caseBluetoothDevice.BOND_BONDING:Log.d("BlueToothTestActivity","正在配对......");break;caseBluetoothDevice.BOND_BONDED:Log.d("BlueToothTestActivity","完成配对");LinkDevice();break;caseBluetoothDevice.BOND_NONE:Log.d("BlueToothTestActivity","未配对");ApadeDevice();default:break;}}}).setNegativeButton("取消",newDialogInterface.OnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){//TODOAuto-generatedmethodstub}}).show();}});}/***第一步,设置蓝牙开启*/privatevoidsetBluetooth(){blueadapter=BluetoothAdapter.getDefaultAdapter();if(blueadapter!=null){//DevicesupportBluetooth//确认开启蓝牙if(!blueadapter.isEnabled()){//请求用户开启Intentintent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent,RESULT_FIRST_USER);//使蓝牙设备可见,方便配对//Intentin=newIntent(//BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,//200);//startActivity(in);//直接开启,不经过提示blueadapter.enable();}findAvalibleDevice();}else{//DevicedoesnotsupportBluetoothAlertDialog.Builderdialog=newAlertDialog.Builder(this);dialog.setTitle("硬件错误");dialog.setMessage("未找到蓝牙设备");dialog.setNegativeButton("取消",newDialogInterface.OnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){}});dialog.show();}}/***第二步,搜索设备*/privatevoidfindAvalibleDevice(){//获取可配对蓝牙设备Set<BluetoothDevice>device=blueadapter.getBondedDevices();userDrivers.clear();deviceList.clear();adapter.notifyDataSetChanged();if(device.size()>0){//存在已经配对过的蓝牙设备for(Iterator<BluetoothDevice>it=device.iterator();it.hasNext();){BluetoothDevicebtd=it.next();userDrivers.add(newUserDriver(btd,true));deviceList.add(btd.getName()+"(已配对)\n"+btd.getAddress());adapter.notifyDataSetChanged();}//搜索没有配对的设备。}//else{//不存在已经配对过的蓝牙设备//deviceList.add("Nocanbematchedtousebluetooth");//adapter.notifyDataSetChanged();//}}/***第三步。查找其他*/publicvoidFindOthers(){//如果正在搜索,就先取消搜索if(blueadapter.isDiscovering()){blueadapter.cancelDiscovery();}if(isFind)return;isFind=true;findAvalibleDevice();//注册用以接收到已搜索到的蓝牙设备的receiverIntentFiltermFilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mReceiver,mFilter);//注册搜索完时的receivermFilter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mReceiver,mFilter);setProgressBarIndeterminateVisibility(true);setTitle("正在扫描....");//开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回blueadapter.startDiscovery();}/***广播处理**/privateBroadcastReceivermReceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){//TODOAuto-generatedmethodstubStringaction=intent.getAction();//获得已经搜索到的蓝牙设备if(action.equals(BluetoothDevice.ACTION_FOUND)){BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//搜索到的不是已经绑定的蓝牙设备if(device.getBondState()!=BluetoothDevice.BOND_BONDED){//显示在TextView上userDrivers.add(newUserDriver(device,false));deviceList.add(device.getName()+"(未配对)\n"+device.getAddress());adapter.notifyDataSetChanged();}//搜索完成}elseif(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){setProgressBarIndeterminateVisibility(false);setTitle("扫描结束");unReceive();isFind=false;}}};/***关闭注册事件*/privatevoidunReceive(){try{//解除注册unregisterReceiver(mReceiver);}catch(Exceptione){//TODO:handleexception}}/***配对并且连接设备*/privatevoidApadeDevice(){try{MethodcreateBondMethod=BluetoothDevice.class.getMethod("createBond");Log.d("BlueToothTestActivity","开始配对1");try{createBondMethod.invoke(userDrivers.get(useIndex).DeviceAdapter);Log.d("BlueToothTestActivity","开始配对2");newThread(newRunnable(){@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubBluetoothDevicebDevice=userDrivers.get(useIndex).DeviceAdapter;while(true){try{Thread.sleep(1000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}//判断配对状态,更新列表信息。if(bDevice.getBondState()==BluetoothDevice.BOND_BONDED){Log.d("BlueToothTestActivity","成功配对");userDrivers.get(useIndex).IsConnected=true;deviceList.set(useIndex,bDevice.getName()+"(已配对)\n"+bDevice.getAddress());Log.d("BlueToothTestActivity","成功配对2");handler2.sendMessage(newMessage());break;}}}}).start();}catch(IllegalArgumentExceptione){//TODOAuto-generatedcatch//blocke.printStackTrace();}catch(IllegalAccessExceptione){//TODOAuto-generatedcatch//blocke.printStackTrace();}catch(InvocationTargetExceptione){//TODOAuto-generatedcatch//blocke.printStackTrace();}}catch(NoSuchMethodExceptione){//TODOAuto-generatedcatch//blocke.printStackTrace();}}@SuppressLint("HandlerLeak")Handlerhandler2=newHandler(){publicvoidhandleMessage(Messagemsg){super.handleMessage(msg);adapter.notifyDataSetChanged();LinkDevice();}};privatevoidLinkDevice(){pDialog.setMessage("连接中....");pDialog.show();newThread(newRunnable(){@Overridepublicvoidrun(){////TODOAuto-generated////connect(userDrivers.get(useIndex).DeviceAdapter);Messagemsg=newMessage();Bundledata=newBundle();UUIDuuid=UUID.fromString(SPP_UUID);try{if(btSocket!=null&&btSocket.isConnected())btSocket.close();btSocket=userDrivers.get(useIndex).DeviceAdapter.createRfcommSocketToServiceRecord(uuid);Log.d("BlueToothTestActivity","开始连接...");btSocket.connect();if(btSocket.isConnected()){data.putString("Request","连接成功");}else{data.putString("Request","连接失败");}}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();data.putString("Request","发生错误");}msg.setData(data);handler.sendMessage(msg);}}).start();}@SuppressLint("HandlerLeak")Handlerhandler=newHandler(){publicvoidhandleMessage(Messagemsg){super.handleMessage(msg);Bundledata=msg.getData();StringvalString=data.getString("Request");if(valString.equals("连接成功")){Intentintent=newIntent(MainActivity.this,Connected.class);startActivity(intent);}else{Toast.makeText(getApplicationContext(),valString,Toast.LENGTH_SHORT).show();//}if(pDialog.isShowing())pDialog.cancel();}};@OverridepublicbooleanonKeyDown(intkeyCode,KeyEventevent){if(keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){if((System.currentTimeMillis()-exitTime)>2000){Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();exitTime=System.currentTimeMillis();}else{if(btSocket!=null&&btSocket.isConnected())try{btSocket.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}finish();System.exit(0);}returntrue;}returnsuper.onKeyDown(keyCode,event);}@OverrideprotectedvoidonDestroy(){//TODOAuto-generatedmethodstubunReceive();super.onDestroy();}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.getMenuInflater().inflate(R.menu.main,menu);returntrue;}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){//Handleactionbaritemclickshere.Theactionbarwill//automaticallyhandleclicksontheHome/Upbutton,solong//asyouspecifyaparentactivityinAndroidManifest.xml.intid=item.getItemId();if(id==R.id.item1){//搜索设备FindOthers();returntrue;}returnsuper.onOptionsItemSelected(item);}}

界面XML:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.example.blt.MainActivity"><ListViewandroid:id="@+id/listView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"></ListView></RelativeLayout>

-------------------------------------------蓝牙的发送和接收!Connected窗体

packagecom.example.blt;importjava.io.InputStream;importjava.io.OutputStream;importandroid.annotation.SuppressLint;importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.text.method.ScrollingMovementMethod;importandroid.util.Log;importandroid.view.KeyEvent;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.TextView;importandroid.widget.TextView.OnEditorActionListener;publicclassConnectedextendsActivity{StringsendData="";boolean_runThread=true;privateTextViewmResults;Threadthread=newThread(newRunnable(){@Overridepublicvoidrun(){Log.d("BlueToothTestActivity","启动线程");StringbufferString="";//TODOAuto-generatedmethodstubwhile(_runThread){if(sendData!=""){Log.d("BlueToothTestActivity","准备数据"+sendData);try{OutputStreamoutputStream=MainActivity.btSocket.getOutputStream();Log.d("BlueToothTestActivity","获得输出流");outputStream.write(sendData.getBytes());Log.d("BlueToothTestActivity","写入输出流");bufferString="send:"+sendData;Log.d("BlueToothTestActivity","已经发送");}catch(Exceptione){//TODO:handleexceptionLog.d("BlueToothTestActivity","发送错误");}sendData="";}try{InputStreaminputStream=MainActivity.btSocket.getInputStream();intcount=inputStream.available();if(count>0){byte[]b=newbyte[count];inputStream.read(b);bufferString="rece:"+newString(b);}}catch(Exceptione){//TODO:handleexception}if(bufferString==null||bufferString=="")continue;Messagemsg=newMessage();Bundledata=newBundle();data.putString("Request",bufferString);msg.setData(data);handler.sendMessage(msg);bufferString="";}}});@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_connected);mResults=(TextView)findViewById(R.id.axis_x);mResults.setMovementMethod(ScrollingMovementMethod.getInstance());mResults.setText("日志信息");thread.start();((Button)findViewById(R.id.BtnSend)).setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){//TODOAuto-generatedmethodstubLog.d("BlueToothTestActivity","点击按钮");sendData=((EditText)findViewById(R.id.editText1)).getText().toString();}});((EditText)findViewById(R.id.editText1)).setOnEditorActionListener(newOnEditorActionListener(){@OverridepublicbooleanonEditorAction(TextViewv,intactionId,KeyEventevent){//TODOAuto-generatedmethodstubLog.d("BlueToothTestActivity","键盘发送");sendData=((EditText)findViewById(R.id.editText1)).getText().toString();returnfalse;}});}//通信模块@SuppressLint("HandlerLeak")Handlerhandler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){super.handleMessage(msg);Bundledata=msg.getData();StringvalString=data.getString("Request");mResults.setText(mResults.getText().toString()+"\r\n"+valString);/**Log.d("BlueToothTestActivity",mResults.getScrollX()+","+*mResults.getScrollY());*/}};@OverridepublicbooleanonKeyDown(intkeyCode,KeyEventevent){if(keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){//dosomething..._runThread=false;Log.d("BlueToothTestActivity","返回了");}returnsuper.onKeyDown(keyCode,event);}/**privatebyte[]getHexBytes(Stringmessage){intlen=message.length()/*2;char[]chars=message.toCharArray();String[]hexStr=new*String[len];byte[]bytes=newbyte[len];for(inti=0,j=0;j<*len;i+=2,j++){hexStr[j]=""+chars[i]+chars[i+1];bytes[j]=*(byte)Integer.parseInt(hexStr[j],16);}returnbytes;}*/@OverridepublicbooleanonCreateOptionsMenu(Menumenu){//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.getMenuInflater().inflate(R.menu.connected,menu);returntrue;}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){//Handleactionbaritemclickshere.Theactionbarwill//automaticallyhandleclicksontheHome/Upbutton,solong//asyouspecifyaparentactivityinAndroidManifest.xml.intid=item.getItemId();if(id==R.id.action_settings){returntrue;}returnsuper.onOptionsItemSelected(item);}}

--------------------------窗体部分

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.example.blt.Connected"><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"android:layout_toLeftOf="@+id/BtnSend"android:digits="0123456789.abcdefghigklmnopqrstuvwxyz"android:ems="10"android:imeOptions="actionSend"android:inputType="textPersonName"><requestFocus/></EditText><Buttonandroid:id="@+id/BtnSend"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/editText1"android:layout_alignBottom="@+id/editText1"android:layout_alignParentRight="true"android:text="Send"/><TextViewandroid:id="@+id/axis_x"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/BtnSend"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:layout_alignRight="@+id/BtnSend"android:scrollbars="vertical"android:text="TextView"/></RelativeLayout>


UserDriver类******************

packagecom.example.blt;importandroid.bluetooth.BluetoothDevice;publicclassUserDriver{//设备信息publicBluetoothDeviceDeviceAdapter=null;//是否已经配对了publicbooleanIsConnected=false;publicUserDriver(BluetoothDevicevalueDevice,booleanisConnected){this.DeviceAdapter=valueDevice;this.IsConnected=isConnected;}}


*************************************************

载入main窗体的时候系统自动侦测是否有蓝牙模块可以使用,当存在的时候,调出已经配对过的设备列表。然后点击菜单里面的扫描。如果扫描到新设备,则加入。

点击设备的时候,如果没有配对的,重新配对,配对过了就跳转到连接界面去。

本文出自 “石头记里看石头” 博客,转载请与作者联系!

更多相关文章

  1. [Android(安卓)GMS 认证] CTS 问题列表之 CtsBluetoothTestCases
  2. 为iPhone,iPad,Android和其他移动设备启用Lync
  3. Android(安卓)获取设备信息
  4. CommandInvokationFailure: Unable to install APK to device.
  5. Android检查设备是否联网
  6. Android中Broadcast的Intent大全
  7. android获取设备空闲空间
  8. Android(安卓)获取设备序列号(SN号)含源码Demo
  9. Android能够获取到唯一的设备ID吗?

随机推荐

  1. android ListView根据字母排序和定位
  2. Erlang实现的百度云推送Android服务端实
  3. Android菜鸟日记3 intent
  4. Android 开发手记一
  5. Android应用开发之RelativeLayout (相对
  6. Android启动脚本init.rc(1)
  7. Android 的源代码结构
  8. 条码扫描二维码扫描—ZXing android 改进
  9. android 测试必备 -adb 工具的使用
  10. Android onDraw