【Android论文栏目提醒】:网学会员为广大网友收集整理了,Android Service和Activity基于串口蓝牙模块的双向通信 - 毕业设计,希望对大家有所帮助!
驱动蓝牙模块可以在 Activity 中直接调用也可以在多线程下直接使用但这样会存在一个缺陷:当你按下手机的 Home 或者 Back 键的时候.程序退出了下次你重新启动软件的时候又需要重新建立蓝牙的链接了. 为了克服以上问题我把蓝牙模块的调用放到 Service 里面使用.首先对 Service 说明下:来源于 http://tianrui-wang-163-com.iteye.com/blog/983099Service 介绍
Android 中的服务和 windows 中的服务是类似的东西,服务一般没有用户操作界面,它运行于系统中不容易被用户发觉,可以使用它开发如监控之类的程序。
由于没有可视化界面,Service 都是从其它程序组件中启动、停止和控制,这些组件包括其它的 Service、Activity 和 Broadcast Receiver。
如果你的应用程序正常且不间断的运行,而不直接依赖于用户输入,Service 是你最佳的选择。
Service 生命周期服务常用生命周期回调方法如下:onCreate 该 方 法 在 服 务 被 创 建 时 调 用 , 该 方 法 只 会 被 调 用 一 次 , 无 论 调 用 多 少 次startService或 bindService方法,服务也只被创建一次。
onDestroy该方法在服务被终止时调用。
Service 对象不能自己启动,需要通过某个 Activity、Service 或者其他 Context 对象来启动。
启动的方法有两种,Context.startService 和 Context.bindService。
两种方式的生命周期是不同的,具体如下所示。
Context.startService 方式的生命周期:启动时,startService –gt onCreate –gt onStart停止时,stopService –gt onDestroyContext.bindService 方式的生命周期:绑定时bindService -gt onCreate –gt onBind解绑定时unbindService –gtonUnbind –gt onDestoryService 实现定义一个 Service 只需要如下两步:第一步:继承 Service 类public class SMSService extends Service 这里可以选择要实现的方法第二步:在 AndroidManifest.xml 文件中的ltapplicationgt节点里对服务进行配置:ltservice
android:namequot.SMSServicequot ”gtlt/servicegt好了废话少说下面从我的代码直接开始:java view plaincopyprintpackage com.lxximport java.io.IOExceptionimport java.io.InputStreamimport java.io.OutputStreamimport java.util.UUIDimport
android.app.Serviceimport
android.bluetooth.BluetoothAdapterimport
android.bluetooth.BluetoothDeviceimport
android.bluetooth.BluetoothSocketimport
android.content.BroadcastReceiverimport
android.content.Contextimport
android.content.Intentimport
android.content.IntentFilterimport
android.os.IBinderimport
android.util.Logpublic class MyService extends Service public boolean threadFlag true MyThread myThread CommandReceiver cmdReceiver//继承自 BroadcastReceiver 对象,用于得到 Activity发送过来的命令 /service 命令/ static final int CMD_STOP_SERVICE 0x01 static final int CMD_SEND_DATA 0x02 static final int CMD_SYSTEM_EXIT 0x03 static final int CMD_SHOW_TOAST 0x04 private BluetoothAdapter mBluetoothAdapter null private BluetoothSocket btSocket null private OutputStream outStream null private InputStream inStream null public boolean bluetoothFlag true private static final UUID MY_UUID UUID.fromStringquot00001101-0000-1000-8000-00805F9B34FBquot private static String address quot00:19:5D:EE:9B:8Fquot // lt要连接的蓝牙设备MAC 地址 Override public IBinder onBindIntent intent // TODO Auto-generated method stub return null Override public void onCreate // TODO Auto-generated method stub super.onCreate //前台 Activity 调用 startService 时,该方法自动执行 Override public int onStartCommandIntent intent int flags int startId // TODO Auto-generated method stub cmdReceiver new CommandReceiver IntentFilter filter new IntentFilter//创建 IntentFilter 对象 //注册一个广播,用于接收 Activity 传送过来的命令,控制 Service 的行为,如:发送数据,停止服务等 filter.addActionquotandroid.intent.action.cmdquot //注册 Broadcast Receiver registerReceivercmdReceiver filter doJob//调用方法启动线程 return super.onStartCommandintent flags startId Override public void onDestroy // TODO Auto-generated method stub super.onDestroy this.unregisterReceivercmdReceiver//取消注册的 CommandReceiver threadFlag false boolean retry true whileretry try myThread.join retry false catchException e e.printStackTrace public class MyThread extends Thread Override public void run // TODO Auto-generated method stub super.run connectDevice//连接蓝牙设备 whilethreadFlag int value readByte ifvalue -1 DisplayToastvalue quotquot try Thread.sleep50 catchException e e.printStackTrace public void doJob mBluetoothAdapter BluetoothAdapter.getDefaultAdapter if mBluetoothAdapter null DisplayToastquot蓝牙设备不可用,请打开蓝牙!quot bluetoothFlag false return if mBluetoothAdapter.isEnabled DisplayToastquot请打开蓝牙并重新运行程序!quot bluetoothFlag false stopService showToastquot请打开蓝牙并重新运行程序!quot return showToastquot搜索到蓝牙设备quot threadFlag true myThread new MyThread myThread.startpublic void connectDevice DisplayToastquot正在尝试连接蓝牙设备,请稍后 quot BluetoothDevice device mBluetoothAdapter.getRemoteDeviceaddress try btSocket device.createRfcommSocketToServiceRecordMY_UUID catch IOException e DisplayToastquot套接字创建失败!quot bluetoothFlag false DisplayToastquot成功连接蓝牙设备!quot mBluetoothAdapter.cancelDiscovery try btSocket.connect DisplayToastquot连接成功建立,可以开始操控了quot showToastquot连接成功建立,可以开始操控了quot bluetoothFlag true catch IOException e try btSocket.close bluetoothFlag false catch IOException e2 DisplayToastquot连接没有建立,无法关闭套接字!quot ifbluetoothFlag try inStream btSocket.getInputStream catch IOException e e.printStackTrace //绑定读接口 try outStream btSocket.getOutputStream catch IOException e e.printStackTrace //绑定写接口 public void sendCmdbyte cmd int value//串口发送数据 ifbluetoothFlag return byte msgBuffer new byte5 msgBuffer0 cmd msgBuffer1 bytevalue gtgt 0 amp 0xff msgBuffer2 bytevalue gtgt 8 amp 0xff msgBuffer3 bytevalue gtgt 16 amp 0xff msgBuffer4 bytevalue gtgt 24 amp 0xff try outStream.writemsgBuffer 0 5 outStream.flush catch IOException e e.printStackTrace public int readByte//return -1 if no data int ret -1 ifbluetoothFlag return ret try ret inStream.read catch IOException e e.printStackTrace return retpublic void stopService//停止服务 threadFlag false//停止线程 stopSelf//停止服务public void showToastString str//显示提示信息 Intent intent new Intent intent.putExtraquotcmdquot CMD_SHOW_TOAST intent.putExtraquotstrquot str intent.setActionquotandroid.intent.action.lxxquot sendBroadcastintent public void DisplayToastString str Log.dquotSeasonquotstr //接收 Activity 传送过来的命令 private class CommandReceiver extends BroadcastReceiver Override public void onReceiveContext context Intent intent ifintent.getAction.equalsquotandroid.intent.action.cmdquot int cmd intent.getIntExtraquotcmdquot -1//获取 Extra 信息 ifcmd CMD_STOP_SERVICE stopService ifcmd CMD_SEND_DATA byte command intent.getByteExtraquotcommandquot byte 0 int value intent.getIntExtraquotvaluequot 0 sendCmdcommandvalue package com.lxximport java.io.IOExceptionimport java.io.InputStreamimport java.io.OutputStreamimport java.util.UUIDimport
android.app.Serviceimport
android.bluetooth.BluetoothAdapterimport
android.bluetooth.BluetoothDeviceimport
android.bluetooth.BluetoothSocketimport
android.content.BroadcastReceiverimport
android.content.Contextimport
android.content.Intentimport
android.content.IntentFilterimport
android.os.IBinderimport
android.util.Logpublic class MyService extends Service public boolean threadFlag true MyThread myThread CommandReceiver cmdReceiver//继承自 BroadcastReceiver 对象,用于得到 Activity发送过来的命令 /service 命令/ static final int CMD_STOP_SERVICE 0x01 static final int CMD_SEND_DATA 0x02 static final int CMD_SYSTEM_EXIT 0x03 static final int CMD_SHOW_TOAST 0x04 private BluetoothAdapter mBluetoothAdapter null private BluetoothSocket btSocket null private OutputStream outStream null private InputStream inStream null public boolean bluetoothFlag true private static final UUID MY_UUID UUID.fromStringquot00001101-0000-1000-8000-00805F9B34FBquot private static String address quot00:19:5D:EE:9B:8Fquot // lt要连接的蓝牙设备MAC 地址 Override public IBinder onBindIntent intent // TODO Auto-generated method stub return null Override public void onCreate // TODO Auto-generated method stub super.onCreate //前台 Activity 调用 startService 时,该方法自动执行 Override public int onStartCommandIntent intent int flags int startId // TODO Auto-generated method stub cmdReceiver new CommandReceiver IntentFilter filter new IntentFilter//创建 IntentFilter 对象 //注册一个广播,用于接收 Activity 传送过来的命令,控制 Service 的行为,如:发送数据,停止服务等 filter.addActionquotandroid.intent.action.cmdquot //注册 Broadcast Receiver registerReceivercmdReceiver filter doJob//调用方法启动线程 return super.onStartCommandintent flags startId Override public void onDestroy // TODO Auto-generated method stub super.onDestroy this.unregisterReceivercmdReceiver//取消注册的 CommandReceiver threadFlag false boolean retry true whileretry try myThread.join retry false catchException e e.printStackTrace public class MyThread extends Thread Override public void run // TODO Auto-generated method stub super.run connectDevice//连接蓝牙设备 whilethreadFlag int value readByte ifvalue -1 DisplayToastvalue quotquot try Thread.sleep50 catchException e e.printStackTrace public void doJob mBluetoothAdapter BluetoothAdapter.getDefaultAdapter if mBluetoothAdapter null DisplayToastquot蓝牙设备不可用,请打开蓝牙!quot bluetoothFlag false return if mBluetoothAdapter.isEnabled DisplayToastquot请打开蓝牙并重新运行程序!quot bluetoothFlag false stopService showToastquot请打开蓝牙并重新运行程序!quot return showToastquot搜索到蓝牙设备quot threadFlag true myThread new MyThread myThread.startpublic void connectDevice DisplayToastquot正在尝试连接蓝牙设备,请稍后 quot BluetoothDevice device mBluetoothAdapter.getRemoteDeviceaddress try btSocket device.createRfcommSocketToServiceRecordMY_UUID catch IOException e DisplayToastquot套接字创建失败!quot bluetoothFlag false DisplayToastquot成功连接蓝牙设备!quot mBluetoothAdapter.cancelDiscovery try btSocket.connect DisplayToastquot连接成功建立,可以开始操控了quot showToastquot连接成功建立,可以开始操控了quot bluetoothFlag true catch IOException e try btSocket.close bluetoothFlag false catch IOException e2 DisplayToastquot连接没有建立,无法关闭套接字!quot ifbluetoothFlag try inStream btSocket.getInputStream catch IOException e e.printStackTrace //绑定读接口 try outStream btSocket.getOutputStream catch IOException e e.printStackTrace //绑定写接口 public void sendCmdbyte cmd int value//串口发送数据 ifbluetoothFlag return byte msgBuffer new byte5 msgBuffer0 cmd msgBuffer1 bytevalue gtgt 0 amp 0xff msgBuffer2 bytevalue gtgt 8 amp 0xff msgBuffer3 bytevalue gtgt 16 amp 0xff msgBuffer4 bytevalue gtgt 24 amp 0xff try outStream.writemsgBuffer 0 5 outStream.flush catch IOException e e.printStackTrace public int readByte//return -1 if no data int ret -1 ifbluetoothFlag return ret try ret inStream.read catch IOException e e.printStackTrace return retpublic void stopService//停止服务 threadFlag false//停止线程 stopSelf//停止服务public void showToastString str//显示提示信息 Intent intent new Intent intent.putExtraquotcmdquot CMD_SHOW_TOAST intent.putExtraquotstrquot str intent.setActionquotandroid.intent.action.lxxquot sendBroadcastintentpublic void DisplayToastString str Log.dquotSeasonquotstr //接收 Activity 传送过来的命令private class CommandReceiver extends BroadcastReceiver Override public void onReceiveContext context Intent intent ifintent.getAction.equalsquotandroid.intent.action.cmdquot int cmd intent.getIntExtraquotcmdquot -1//获取 Extra 信息 ifcmd CMD_STOP_SERVICE stopService ifcmd CMD_SEND_DATA byte command intent.getByteExtraquotcommandquot byte 0 int value intent.getIntExtraquotvaluequot 0 sendCmdcommandvalue 主界面 Activity 只有一个按钮就是通过 Broadcast 来想 Service 发送数据Service 收到数据进行命令等的解析然后调用相应的函数相当于直接调用了 Service 中的函数.因为Activity 和 Service 是运行在不同的进程中的两者不能进行直接的通讯必须通过一个quot桥梁quot建立起联系才行.java view plaincopyprintpackage com.lxximport
android.app.Activityimport
android.content.BroadcastReceiverimport
android.content.Contextimport
android.content.Intentimport
android.content.IntentFilterimport
android.os.Bundleimport
android.os.IBinderimport
android.view.Viewimport
android.view.View.OnClickListenerimport
android.widget.Buttonimport
android.widget.TextViewimport
android.widget.Toastpublic class BroadcastActivity extends Activity / Called when the activity is first created. /TextView myTextViewButto.