解决这个J2ME蓝牙异常

时间:2011-11-29 07:35:42

标签: java-me jsr82

我是J2ME的新手。我正在学习J2ME蓝牙应用程序开发。我写了一些简单的代码来获取本地蓝牙设备的名称。它在模拟器中工作正常。但是当我在手机中试用它时,它会抛出错误。

  1. 如果手机中的蓝牙已关闭,则会抛出:javax.bluetooth.BlueToothStateException
  2. 如果手机中的蓝牙已开启,则会抛出: javax.bluetooth.bluetoothstateexception: initialize - GetProperty failed
  3. 请帮我摆脱这个错误,以便我可以继续学习。

    这是我的代码:

    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.bluetooth.*;
    
    public class BluetoothApp3Midlet extends MIDlet implements CommandListener
    {
    private Display display;
    private Form form;
    private Command exit;
    private LocalDevice local = null;
    
    public void BluetoothApp3Midlet()
    {
    
    }
    
    public void startApp() 
    {
        form = new Form("Bluetooth Details");
        exit = new Command("Exit",Command.EXIT,1);
        form.addCommand(exit);
        form.setCommandListener(this);
        display = Display.getDisplay(this);
        form.append("Hello");
        form.append("World");
        if(hasBluetoothAPI())
        {
            try
            {
                local = LocalDevice.getLocalDevice();
                String address = local.getBluetoothAddress();
                String name = local.getFriendlyName();
                form.append("Address: "+address+"\n");
                form.append("Name: "+name+"\n");
            }
            catch(Exception e)
            {
                form.append("Error: "+e+"\n");
            }
        }
        else
        {
            form.append("BluetoothAPI not found\n");
        }
    
        display.setCurrent(form);
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
    
    public void commandAction(Command cmd, Displayable d)
    {
        if( cmd == exit )
        {
            this.destroyApp(true);
            this.notifyDestroyed();
        }
    }
    
    public static boolean hasBluetoothAPI ()
    {
        try
        {
            Class.forName ("javax.bluetooth.LocalDevice");
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    }
    

2 个答案:

答案 0 :(得分:2)

您的代码不完整。您需要实现此tutorial中描述的其他方法。

本教程非常好地介绍了蓝牙连接。

您还可以查看this PDF文件。

答案 1 :(得分:1)

您必须在代码中添加DiscoveryAgent,例如:

DiscoveryAgent agent;
agent=local.getdiscoveryagent(discoveryagent.giac,this);
agent.startinquiry(discoveryagent.giac,this);