当前位置: 首页 > news >正文

使用J2ME搜索蓝牙设备,并与搜到的设备通信

本文来自http://blog.csdn.net/hellogv/
由于代码来自我目前的项目,所以不能给出完整代码(非常多),只给出关键代码,对于一般J2ME程序员绝对看得懂!
首先,给出J2ME搜索蓝牙设备的代码:
public void commandAction(Command command, Displayable displayable)

        {

             if(command==cmd_Search)

             {

                 try 

                 {

                     LocalDevice localDevice = LocalDevice.getLocalDevice();

                     DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();

                     discoveryAgent.startInquiry(DiscoveryAgent.GIAC,new MyDiscoveryListener(this));

                 } 

                 catch (Exception e) 

                 {

                     MyClass.MessageBox("搜索出错,找不到蓝牙设备!", display);

                     return;

                 }

                 

                 Menu.removeCommand(cmd_Search);

             }

        } 

}





class MyDiscoveryListener implements DiscoveryListener {

    //用于保存搜索到的设备

    Vector devices = new Vector();

    SearchDevices midlet;

    

    public MyDiscoveryListener(SearchDevices midlet) {

        this.midlet = midlet;

    }

    

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

        devices.addElement(btDevice);

    }

    

    public void inquiryCompleted(int discType) {

            for (int i=0;i<devices.size();i++) 

            {

                RemoteDevice btDevice = (RemoteDevice)devices.elementAt(i);

                try 

                {

                    String device_address=btDevice.getBluetoothAddress();//取得蓝牙设备的全球唯一地址

        } 

                catch (Exception e) {e.printStackTrace();}

            }

    }

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {}

    public void serviceSearchCompleted(int transID, int responseCode) {}

    

}



接下来就是根据搜索所得的蓝牙设备地址来连接设备,并与设备通信:

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import javax.bluetooth.ServiceRecord;

import javax.microedition.io.Connector;

import javax.microedition.io.StreamConnection;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Display;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

import javax.microedition.lcdui.TextField;

import javax.microedition.midlet.MIDlet;

import javax.microedition.midlet.MIDletStateChangeException;



public class MIDlet_ConnDevice extends MIDlet 

implements  Runnable, CommandListener {

    private Display display = null;



    

    private Form form = new Form("蓝牙 ");

    //用于输入要发送的消息

    private TextField tfData = new TextField("请输入发送的消息",

            "",255,TextField.ANY);

    

    private Command cmdExit = new Command("退出", Command.EXIT, 0);

    private Command cmdSend = new Command("发送", Command.SCREEN, 1);

    private Command cmdConnect = new Command("连接", Command.SCREEN, 1);

    

    //线程运行标志

    private boolean isRunning = true;

    

    StreamConnection client = null;

    //服务器服务记录

    ServiceRecord record=null;

    private DataInputStream dis = null;

    private DataOutputStream dos = null;

   

    public MIDlet_ConnDevice() {

        super();

        form.append(tfData);

        form.addCommand(cmdExit);

        form.addCommand(cmdConnect);

        form.setCommandListener(this);  

    }

    protected void startApp() throws MIDletStateChangeException {

        display = Display.getDisplay(this);

        display.setCurrent(form);

    }



    protected void pauseApp() {

        isRunning = false;

        close();

    }



    protected void destroyApp(boolean arg0)

        throws MIDletStateChangeException {

        isRunning = false;

        close();

    }

    

    /**

     * 处理命令按钮事件

     */

    public void commandAction(Command cmd, Displayable d) {

        if (cmd == cmdExit) {  

            isRunning = false;

            notifyDestroyed();

        } else if(cmd == cmdSend) {

            //发送数据

            new Thread() {

                public void run() {

                    if (dos == null) {

                        return;

                    }

                    //把输入的字符串变为数字

                        try {   

                                 

                            dos.writeUTF(tfData.getString());                     

                            dos.flush();                    

                        } catch (IOException e) {                        

                            form.append("Send error");         

                    }

                }

            }.start();

        } else if (cmd == cmdConnect) {

            //开始服务器线程

            new Thread(this).start();

        }

    }     

    

    /**

     * 客户端接收线程

     */

    public void run() {

        isRunning = true;

        client = null;

        String device_address;//搜索所得的设备地址

        String conURL = "btspp://"+device_address+":1";

        try {

            client = (StreamConnection)Connector.open(conURL);

            form.append("Connected!\n");

            dis = client.openDataInputStream();

            dos = client.openDataOutputStream();

            form.removeCommand(cmdConnect);

            form.addCommand(cmdSend);

        } catch (Exception e) {

                form.append("connect error");

                close();

            return;

        }

        while(isRunning) {

            try {

                        if(dis.available()>1)

                        {

                            byte[] rec_package=new byte[dis.available()];//强烈建议这里使用byte[]

                            dis.read(rec_package);

                            String str=new String(rec_package);

                        }

            }

                catch (Exception e) {

                       form.append("rec error");

                break;

            }

        }

        close();

        form.removeCommand(cmdSend);

        form.addCommand(cmdConnect);

    }

    

    /**

     * 关闭连接

     */

    public void close() {

        try {

            if (dis != null) {

                dis.close();

                dis = null;

            }

            

            if (dos != null) {

                dos.close();

                dos = null;

            }

            

            if (client != null) {

                client.close();

                client = null;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }



}



<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 11"> <meta name="Originator" content="Microsoft Word 11"> <link rel="File-List" href="file:///G:%5CDOCUME~1%5CADMINI~1%5CLOCALS~1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml"> <!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning /> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL /> <w:BalanceSingleByteDoubleByteWidth /> <w:DoNotLeaveBackslashAlone /> <w:ULTrailSpace /> <w:DoNotExpandShiftReturn /> <w:AdjustLineHeightInTable /> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:UseFELayout /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><style type="text/css"> <!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"\@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style> <![endif]-->

相关文章:

  • 知识产权保护,在中国是一纸空谈么?
  • LeetCode 6: ZigZag Conversion
  • 一段时间没来,blog升级了?
  • Google 的怪异域名大全
  • 机器学习中的方差偏差分析(Bias-variance analysis)
  • 新爹手记-分娩篇-生男生女
  • Web环境下SVG地图浏览器的设计与实现
  • 基于SVG的WebGIS地图搜索研究与实现
  • 程序员教你不背单词学英语!流利英语一周成!!!
  • 工业标准的矢量图像格式----SVG
  • 一个关于遗传算法的java小实验(吃豆人)
  • Nvidia副总裁称“CPU已死,GPU当立”
  • 宽度学习(Broad Learning System)
  • Mock in JUnit
  • 用概率告诉你:集齐 “五福” 要多久
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • Golang-长连接-状态推送
  • Node项目之评分系统(二)- 数据库设计
  • scala基础语法(二)
  • Spring声明式事务管理之一:五大属性分析
  • vue 配置sass、scss全局变量
  • vue-router的history模式发布配置
  • Webpack 4x 之路 ( 四 )
  • 搞机器学习要哪些技能
  • 如何学习JavaEE,项目又该如何做?
  • 使用 5W1H 写出高可读的 Git Commit Message
  • 线性表及其算法(java实现)
  • 找一份好的前端工作,起点很重要
  • nb
  • 2017年360最后一道编程题
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • ​io --- 处理流的核心工具​
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • #DBA杂记1
  • #git 撤消对文件的更改
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #我与Java虚拟机的故事#连载02:“小蓝”陪伴的日日夜夜
  • #在 README.md 中生成项目目录结构
  • $(selector).each()和$.each()的区别
  • (HAL)STM32F103C6T8——软件模拟I2C驱动0.96寸OLED屏幕
  • (搬运以学习)flask 上下文的实现
  • (第27天)Oracle 数据泵转换分区表
  • (附源码)ssm码农论坛 毕业设计 231126
  • (规划)24届春招和25届暑假实习路线准备规划
  • (实战)静默dbca安装创建数据库 --参数说明+举例
  • (已解决)vue+element-ui实现个人中心,仿照原神
  • (原創) X61用戶,小心你的上蓋!! (NB) (ThinkPad) (X61)
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .NET Compact Framework 多线程环境下的UI异步刷新
  • .NetCore部署微服务(二)
  • .net分布式压力测试工具(Beetle.DT)
  • .Net高阶异常处理第二篇~~ dump进阶之MiniDumpWriter
  • .NET正则基础之——正则委托
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • ::前边啥也没有