HardBirch

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

时间:08-04-24 栏目:安卓入门与提高 作者:张飞不张,文采横飞 评论:9 点击: 3,012 次

  


 由于代码来自我目前的项目,所以不能给出完整代码(非常多),只给出关键代码,对于一般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();

        }

    }

}

 

 

声明: 本文由( 张飞不张,文采横飞 )原创编译,转载请保留链接: 使用J2ME搜索蓝牙设备,并与搜到的设备通信

使用J2ME搜索蓝牙设备,并与搜到的设备通信:目前有9 条留言

  1. 9楼
    money:

    很好很强大!

    2008-05-14 10:09 [回复]
  2. 8楼
    read123:

    呵呵,这篇文章上过“移动”频道首页,呵呵,领教了

    2008-05-28 09:55 [回复]
  3. 7楼
    TM_LiuYan:

    请教下为什么下面代码不执行CommadnAction的呀?form.append无效
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.MIDletStateChangeException;

    public class DisplayableDemo extends MIDlet implements CommandListener {
    Display display = null;
    Form form= new Form("演示DisplayAble对象");
    //创建按钮
    static final Command cmdGetTitle= new Command("获得标题",Command.ITEM,1);
    static final Command cmdSetTitle=new Command("设置标题",Command.ITEM,1);
    static final Command cmdGetWidth=new Command("显示宽度",Command.ITEM,1);
    static final Command cmdGetHeight=new Command("显示高度",Command.ITEM,1);
    // static final Command cmdExit =new Command("退出",Command.STOP,2);

    int count=0;
    public DisplayableDemo() {
    // TODO 自动生成构造函数存根
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    // TODO 自动生成方法存根
    notifyDestroyed();

    }

    protected void pauseApp() {
    // TODO 自动生成方法存根

    }

    protected void startApp() throws MIDletStateChangeException {
    form.addCommand(cmdGetTitle);
    form.addCommand(cmdSetTitle);
    form.addCommand(cmdGetWidth);
    form.addCommand(cmdGetHeight);
    //form.append("xxx");
    //form.addCommand(cmdExit);
    display=Display.getDisplay(this);
    display.setCurrent(form);
    // TODO 自动生成方法存根
    }<b

    2008-09-06 16:14 [回复]
  4. 6楼
    TM_LiuYan:

    public void commandAction(Command C,Displayable d)
    {
    //form.append("当前标题:"+form.getTitle()+"/n");
    // String label=C.getLabel();
    //if (label.equals("退出"))
    //// {

    // destroyApp(true);
    //}
    if (C==cmdGetTitle)
    {

    form.append("当前标题:"+form.getTitle()+"/n");
    }else if(C==cmdSetTitle)
    {

    count++;
    form.setTitle("this is new "+count+"title/n");
    }else if(C==cmdGetWidth)
    {

    form.append("现在宽度是:"+form.getWidth()+"/n");
    }else if(C==cmdGetHeight)
    {

    form.append("高度:"+form.getHeight()+"/n");
    }

    }

    }

    2008-09-06 16:15 [回复]
  5. 5楼
    hellogv:

    form.setCommandListener(this);

    2008-09-07 08:53 [回复]
  6. 4楼
    TM_LiuYan:

    谢谢,按照你的提示已经解决

    2008-09-08 21:51 [回复]
  7. 地板
    biaozai06:

    多谢分享!!

    2008-12-08 17:37 [回复]
  8. 板凳
    小博:

    怎么把他放在手机上呀 我打包后生成JAD 但是放到手机上说无效

    2008-12-29 14:28 [回复]
  9. 沙发
    小博:

    怎么把他放在手机上呀 我打包后生成JAD 但是放到手机上说无效

    2008-12-29 14:28 [回复]

发表评论


QQ群互动

Linux系统与内核学习群:194051772

WP建站技术学习交流群:194062106

魔豆之路QR

魔豆的Linux内核之路

魔豆的Linux内核之路

优秀工程师当看优秀书籍

优秀程序员,要看优秀书!

赞助商广告

友荐云推荐