service启动activity Android Service和Activity基于串口蓝牙模块的双向通信.doc
文本预览下载声明
service启动activity Android Service和Activity基于串口蓝牙模块的双向通信
导读:就爱阅读网友为您分享以下“Android Service和Activity基于串口蓝牙模块的双向通信”的资讯,希望对您有所帮助,感谢您对92的支持!
null;private OutputStream outStream = null;private InputStream inStream = null;public boolean bluetoothFlag = true;private static final UUID MY_UUID = UUID.fromString(quot0000-1000-8000-00805F9B34FBquot;);private static String address = quot;00:19:5D:EE:9B:8Fquot;; // lt;==要连接的蓝牙设备MAC地址@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}//前台Activity调用startService时,该方法自动执行@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubcmdReceiver = new CommandReceiver();IntentFilter filter = new IntentFilter();//创建IntentFilter对象//注册一个广播,用于接收Activity传送过来的命令,控制Service的行为,如:发送数据,停止服务等filter.addAction(quot;ent.action.cmdquot;);//注册Broadcast ReceiverregisterReceiver(cmdReceiver, filter);doJob();//调用方法启动线程return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiverthreadFlag = false;boolean retry = true;while(retry){try{ myThread.join();retry = false;}catch(Exception e){e.printStackTrace();}}}public class MyThread extends Thread{ @Overridepublic void run() {// TODO Auto-generated method stubsuper.run();connectDevice();//连接蓝牙设备while(threadFlag){int value = readByte();if(value != -1){DisplayToast(value + quot;quot;);}try{Thread.sleep(50);}catch(Exception e){e.printStackTrace();} }}}public void doJob(){mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) { DisplayToast(quot;蓝牙设备不可用,请打开蓝牙!quot;);bluetoothFlag = false;return;}if (!mBluetoothAdapter.isEnabled()) {DisplayToast(quot;请打开蓝牙并重新运行程序!quot;);bluetoothFlag = false;stopService();showToast(quot;请打开蓝牙并重新运行程序!quot;);return;}
显示全部