使用J2ME搜尋藍牙裝置,並與搜到的裝置通訊

來源:互聯網
上載者:User
本文來自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();        }    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.