基于蓝牙的文本交互程序设计.docx_第1页
基于蓝牙的文本交互程序设计.docx_第2页
基于蓝牙的文本交互程序设计.docx_第3页
基于蓝牙的文本交互程序设计.docx_第4页
基于蓝牙的文本交互程序设计.docx_第5页
已阅读5页,还剩13页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

246实验三基于蓝牙的文本交互程序设计实验三基于蓝牙的文本交互程序设计一、实验目的1.理解蓝牙的协议体系结构。2.理解蓝牙设备通信的原理与流程。3.掌握Android平台上蓝牙数据传输程序的设计思想和基本框架。二、实验内容在Android平台上(也可选择iOS和WindowsPhone平台)编写一程序,实现蓝牙开启、蓝牙设备扫描、蓝牙设备连接和文本交互等功能。三、实验仪器与设备PC机1台,智能手机2部。四、程序思想程序需要实现手机蓝牙功能检测、蓝牙开启、设备扫描、设备互连和文本通信等功能。蓝牙设备互连的流程如算法1所示。算法1蓝牙设备互连算法beginif(手机没有蓝牙适配器)return;if(手机蓝牙功能未开启)打开蓝牙;if(蓝牙适配器对其它设备不可见)使蓝牙适配器对其它设备可见300秒;/时间可设置,范围0-3600秒switch(连接方式)case安全连接:扫描周边蓝牙设备;显示已配对设备和其它可连接设备列表;if(用户选择其它可连接设备)两端设备配对;连接用户选择的对端设备;break;case不安全连接:扫描周边蓝牙设备;显示已配对设备和其它可连接设备列表;无线网络技术247连接用户选择的对端设备;break;文本通信;断开连接;end程序中需要用到android.bluetooth包中的一些类,这些类的功能如下:1)BluetoothAdapter表示本地蓝牙适配器。可完成蓝牙适配器对其它设备可见,查询已配对蓝牙设备,扫描周边蓝牙设备和创建BluetoothServerSocket对象等功能。2)BluetoothDevice表示远端蓝牙设备。可查询远端设备的名字,地址和配对状态等信息。可通过BluetoothSocket对象连接对端设备。3)BluetoothSocket表示蓝牙socket接口。这是一个连接点,允许应用通过InputStream和OutputStream与另一个蓝牙设备交换数据。4)BluetoothServerSocket表示服务器socket,监听连接请求。为了连接两个设备,一个设备必须使用这个类打开服务器socket。当对端设备发送连接请求时,若请求被接受,BluetoothServerSocket将返回一个已连接的BluetoothSocket。五、实验步骤及要求1.建立AndroidStudio工程。工程的Applicationname和CompanyDomain可自行命名,但应符合相关规范。此处两者分别命名为BTTexInter和well.ren。选择工程的存储位置。APP运行的formfactor选择PhoneandTablet,MinimumSDK选择Android4.1。activity选择BlankActivity。工程建立后,会产生一系列文件和文件夹,其中有AndroidManfest.xml、activity_main.xml、menu_main.xml、strings.xml和MainActivity.java等文件。2.新建activity_device_list.xml、device_name.xml、message.xml、DeviceListActivity.java、Constants.java和BTTexInterCliServ.java文件。完整的工程文件结构如图1所示。3.撰写与修改程序代码。1)修改AndroidManfest.xml文件代码。加入对权限和activity的声明。代码如下:248实验三基于蓝牙的文本交互程序设计图1工程文件结构2)修改strings.xml文件。这里存放程序中用到的字符串常量。完整的代码如下:BTTexInterSettingsSendYouarenotconnectedtoadeviceBluetoothwasnotenabled.LeavingBluetoothInteractive.connecting.无线网络技术249connectedto%1$snotconnectedscanningfordevices.selectadevicetoconnectNodeviceshavebeenpairedNodevicesfoundPairedDevicesOtherAvailableDevicesScanfordevicesConnectadevice-SecureConnectadevice-InsecureMakediscoverable3)撰写MainActivity.java文件代码。这部分代码完成加载文本交互界面,蓝牙功能开启,蓝牙适配器可见和交互文本的显示等功能。完整的代码如下:packageren.well.bttexinter;importandroid.app.Activity;importandroid.bluetooth.BluetoothAdapter;importandroid.bluetooth.BluetoothDevice;importandroid.content.Intent;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.support.v7.app.ActionBar;importandroid.support.v7.app.ActionBarActivity;importandroid.util.Log;importandroid.view.KeyEvent;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.inputmethod.EditorInfo;importandroid.widget.ArrayAdapter;importandroid.widget.Button;importandroid.widget.EditText;250实验三基于蓝牙的文本交互程序设计importandroid.widget.ListView;importandroid.widget.TextView;importandroid.widget.Toast;publicclassMainActivityextendsActionBarActivityprivatestaticfinalStringTAG=BTTexInteractiveMAIN;/IntentrequestcodesprivatestaticfinalintREQUEST_CONNECT_DEVICE_SECURE=1;privatestaticfinalintREQUEST_CONNECT_DEVICE_INSECURE=2;privatestaticfinalintREQUEST_ENABLE_BT=3;/LayoutViewsprivateListViewmConversationView;privateEditTextmOutEditText;privateButtonmSendButton;/NameoftheconnecteddeviceprivateStringmConnectedDeviceName=null;/ArrayadapterfortheconversationthreadprivateArrayAdaptermConversationArrayAdapter;/StringbufferforoutgoingmessagesprivateStringBuffermOutStringBuffer;/LocalBluetoothadapterprivateBluetoothAdaptermBluetoothAdapter=null;/MemberobjectforthechatservicesprivateBTTexInterCliServmInterCliServ=null;OverrideprotectedvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mConversationView=(ListView)this.findViewById(R.id.in);mOutEditText=(EditText)this.findViewById(R.id.edit_text_out);mSendButton=(Button)this.findViewById(R.id.button_send);无线网络技术251/GetlocalBluetoothadaptermBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();/Iftheadapterisnull,thenBluetoothisnotsupportedif(mBluetoothAdapter=null)Toast.makeText(this,Bluetoothisnotavailable,Toast.LENGTH_LONG).show();this.finish();publicvoidonStart()super.onStart();/IfBTisnoton,requestthatitbeenabled./setupChat()willthenbecalledduringonActivityResultif(!mBluetoothAdapter.isEnabled()IntentenableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableIntent,REQUEST_ENABLE_BT);/Otherwise,setupthechatsessionelseif(mInterCliServ=null)setupChat();OverridepublicvoidonDestroy()super.onDestroy();if(mInterCliServ!=null)mInterCliServ.stop();OverridepublicvoidonResume()super.onResume();/PerformingthischeckinonResume()coversthecaseinwhichBTwas/notenabledduringonStart(),sowewerepausedtoenableit./onResume()willbecalledwhenACTION_REQUEST_ENABLEactivityreturns.if(mInterCliServ!=null)/OnlyifthestateisSTATE_NONE,doweknowthatwehaventstarted252already实验三基于蓝牙的文本交互程序设计if(mInterCliServ.getState()=BTTexInterCliServ.STATE_NONE)/StarttheBluetoothchatservicesmInterCliServ.start();/*SetuptheUIandbackgroundoperationsforchat.*/privatevoidsetupChat()Log.d(TAG,setupChat();/InitializethearrayadapterfortheconversationthreadmConversationArrayAdapter=newArrayAdapter(this,R.layout.message);mConversationView.setAdapter(mConversationArrayAdapter);/InitializethecomposefieldwithalistenerforthereturnkeymOutEditText.setOnEditorActionListener(mWriteListener);/InitializethesendbuttonwithalistenerthatforclickeventsmSendButton.setOnClickListener(newView.OnClickListener()publicvoidonClick(Viewv)/Sendamessageusingcontentoftheedittextwidget/Viewview=getWindow().getDecorView();Viewview=getCurrentFocus();if(null!=view)TextViewtextView=(TextView)view.findViewById(R.id.edit_text_out);Stringmessage=textView.getText().toString();sendMessage(message););/InitializetheBTTexInterCliServtoperformbluetoothconnectionsmInterCliServ=newBTTexInterCliServ(this,mHandler);无线网络技术253/InitializethebufferforoutgoingmessagesmOutStringBuffer=newStringBuffer();/*Makesthisdevicediscoverable.*/privatevoidensureDiscoverable()if(mBluetoothAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)IntentdiscoverableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);startActivity(discoverableIntent);/*Sendsamessage.*parammessageAstringoftexttosend.*/privatevoidsendMessage(Stringmessage)/Checkthatwereactuallyconnectedbeforetryinganythingif(mInterCliServ.getState()!=BTTexInterCliServ.STATE_CONNECTED)Toast.makeText(this,R.string.not_connected,Toast.LENGTH_SHORT).show();return;/Checkthattheresactuallysomethingtosendif(message.length()0)/GetthemessagebytesandtelltheBTTexInterCliServtowritebytesend=message.getBytes();mInterCliServ.write(send);/ResetoutstringbuffertozeroandcleartheedittextfieldmOutStringBuffer.setLength(0);mOutEditText.setText(mOutStringBuffer);254实验三基于蓝牙的文本交互程序设计/*TheactionlistenerfortheEditTextwidget,tolistenforthereturnkey*/privateTextView.OnEditorActionListenermWriteListener=newTextView.OnEditorActionListener()publicbooleanonEditorAction(TextViewview,intactionId,KeyEventevent)/Iftheactionisakey-upeventonthereturnkey,sendthemessageif(actionId=EditorInfo.IME_NULL&event.getAction()=KeyEvent.ACTION_UP)Stringmessage=view.getText().toString();sendMessage(message);returntrue;/*Updatesthestatusontheactionbar.*paramresIdastringresourceID*/privatevoidsetStatus(intresId)finalActionBaractionBar=getSupportActionBar();if(null=actionBar)return;actionBar.setSubtitle(resId);/*Updatesthestatusontheactionbar.*paramsubTitlestatus*/privatevoidsetStatus(CharSequencesubTitle)finalActionBaractionBar=getSupportActionBar();if(null=actionBar)return;无线网络技术255actionBar.setSubtitle(subTitle);/*TheHandlerthatgetsinformationbackfromtheBTTexInterCliServ*/privatefinalHandlermHandler=newHandler()OverridepublicvoidhandleMessage(Messagemsg)/FragmentActivityactivity=getActivity();switch(msg.what)caseConstants.MESSAGE_STATE_CHANGE:switch(msg.arg1)caseBTTexInterCliServ.STATE_CONNECTED:setStatus(getString(R.string.title_connected_to,mConnectedDeviceName);mConversationArrayAdapter.clear();break;caseBTTexInterCliServ.STATE_CONNECTING:setStatus(R.string.title_connecting);break;caseBTTexInterCliServ.STATE_LISTEN:caseBTTexInterCliServ.STATE_NONE:setStatus(R.string.title_not_connected);break;break;caseConstants.MESSAGE_WRITE:bytewriteBuf=(byte)msg.obj;/constructastringfromthebufferStringwriteMessage=newString(writeBuf);mConversationArrayAdapter.add(Me:+writeMessage);break;caseConstants.MESSAGE_READ:bytereadBuf=(byte)msg.obj;/constructastringfromthevalidbytesinthebufferStringreadMessage=newString(readBuf,0,msg.arg1);mConversationArrayAdapter.add(mConnectedDeviceName+:+readMessage);break;256实验三基于蓝牙的文本交互程序设计caseConstants.MESSAGE_DEVICE_NAME:/savetheconnecteddevicesnamemConnectedDeviceName=msg.getData().getString(Constants.DEVICE_NAME);if(null!=MainActivity.this)Toast.makeText(MainActivity.this,Connectedto+mConnectedDeviceName,Toast.LENGTH_SHORT).show();break;caseConstants.MESSAGE_TOAST:if(null!=MainActivity.this)Toast.makeText(MainActivity.this,msg.getData().getString(Constants.TOAST),Toast.LENGTH_SHORT).show();break;publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata)switch(requestCode)caseREQUEST_CONNECT_DEVICE_SECURE:/WhenDeviceListActivityreturnswithadevicetoconnectif(resultCode=Activity.RESULT_OK)connectDevice(data,true);break;caseREQUEST_CONNECT_DEVICE_INSECURE:/WhenDeviceListActivityreturnswithadevicetoconnectif(resultCode=Activity.RESULT_OK)connectDevice(data,false);break;caseREQUEST_ENABLE_BT:/WhentherequesttoenableBluetoothreturnsif(resultCode=Activity.RESULT_OK)/Bluetoothisnowenabled,sosetupachatsessionsetupChat();else无线网络技术257/UserdidnotenableBluetoothoranerroroccurredLog.d(TAG,BTnotenabled);Toast.makeText(this,R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();this.finish();/*Establishconnectionwithotherdevice*paramdataAnlinkIntentwithlinkDeviceListActivity#EXTRA_DEVICE_ADDRESSextra.*paramsecureSocketSecuritytype-Secure(true),Insecure(false)*/privatevoidconnectDevice(Intentdata,booleansecure)/GetthedeviceMACaddressStringaddress=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);/GettheBluetoothDeviceobjectBluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);/AttempttoconnecttothedevicemInterCliServ.connect(device,secure);OverridepublicbooleanonCreateOptionsMenu(Menumenu)/Inflatethemenu;thisaddsitemstotheactionbarifitispresent.getMenuInflater().inflate(R.menu.menu_main,menu);returntrue;OverridepublicbooleanonOptionsItemSelected(MenuItemitem)/Handleactionbaritemclickshere.Theactionbarwill/automaticallyhandleclicksontheHome/Upbutton,solong/asyouspecifyaparentactivityinAndroidMitemId=item.getItemId();switch(itemId)caseR.id.secure_connect_scan:/LaunchtheDeviceListActivitytoseedevicesanddoscan258实验三基于蓝牙的文本交互程序设计IntentserverIntent=newIntent(this,DeviceListActivity.class);startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE_SECURE);returntrue;caseR.id.insecure_connect_scan:/LaunchtheDeviceListActivitytoseedevicesanddoscanIntentserverIntent=newIntent(this,DeviceListActivity.class);startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE_INSECURE);returntrue;caseR.id.discoverable:/EnsurethisdeviceisdiscoverablebyothersensureDiscoverable();returntrue;returnsuper.onOptionsItemSelected(item);4)撰写DeviceListActivity.java文件代码。这部分代码完成已配对设备的获取与显示、周边蓝牙设备的扫描与显示及返回用户选择的对端设备MAC地址等功能。完整的代码如下:packageren.well.bttexinter;importandroid.app.Activity;importandroid.bluetooth.BluetoothAdapter;importandroid.bluetooth.BluetoothDevice;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;importandroid.view.Window;importandroid.widget.AdapterView;importandroid.widget.ArrayAdapter;importandroid.widget.Button;importandroid.widget.ListView;importandroid.widget.TextView;无线网络技术259importjava.util.Set;/*ThisActivityappearsasadialog.Itlistsanypaireddevicesand*devicesdetectedintheareaafterdiscovery.Whenadeviceischosen*bytheuser,theMACaddressofthedeviceissentbacktotheparent*ActivityintheresultIntent.*/publicclassDeviceListActivityextendsActivity/TagforLogprivatestaticfinalStringTAG=DeviceListActivity;/ReturnIntentextrapublicstaticStringEXTRA_DEVICE_ADDRESS=device_address;/MemberfieldsprivateBluetoothAdaptermBtAdapter;/NewlydiscovereddevicesprivateArrayAdaptermNewDevicesArrayAdapter;OverrideprotectedvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);/SetupthewindowrequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);setContentView(R.layout.activity_device_list);/SetresultCANCELEDincasetheuserbacksoutsetResult(Activity.RESULT_CANCELED);/InitializethebuttontoperformdevicediscoveryButtonscanButton=(Button)findViewById(R.id.button_scan);scanButton.setOnClickListener(newView.OnClickListener()publicvoidonClick(Viewv)doDiscovery();v.setVisibility(View.GONE););/Initializearrayadapters.Oneforalreadypaireddevicesand/onefornewlydiscovereddevices260实验三基于蓝牙的文本交互程序设计ArrayAdapterpairedDevicesArrayAdapter=newArrayAdapter(this,R.layout.device_name);mNewDevicesArrayAdapter=newArrayAdapter(this,R.layout.device_name);/FindandsetuptheListViewforpaireddevicesListViewpairedListView=(ListView)findViewById(R.id.paired_devices);pairedListView.setAdapter(pairedDevicesArrayAdapter);pairedListView.setOnItemClickListener(mDeviceClickListener);/FindandsetuptheListViewfornewlydiscovereddevicesListViewnewDevicesListView=(ListView)findViewById(R.id.new_devices);newDevicesListView.setAdapter(mNewDevicesArrayAdapter);newDevicesListView.setOnItemClickListener(mDeviceClickListener);/RegisterforbroadcastswhenadeviceisdiscoveredIntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(mReceiver,filter);/Registerforbroadcastswhendiscoveryhasfinishedfilter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(mReceiver,filter);/GetthelocalBluetoothadaptermBtAdapter=BluetoothAdapter.getDefaultAdapter();/GetasetofcurrentlypaireddevicesSetpairedDevices=mBtAdapter.getBondedDevices();/Iftherearepaireddevices,addeachonetotheArrayAdapterif(pairedDevices.size()0)findViewBy

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论