0

我是 J2ME 的新手。我正在学习 J2ME 蓝牙应用程序开发。我编写了一些简单的代码来获取本地蓝牙设备的名称。它在模拟器中运行良好。但是当我在手机中尝试它时,它会引发以下错误。

  1. 如果我手机中的蓝牙关闭,则会抛出:javax.bluetooth.BlueToothStateException.
  2. 如果我手机中的蓝牙已打开,则会抛出: javax.bluetooth.bluetoothstateexception: initialize - GetProperty failed

请帮助我摆脱这个错误,以便我可以继续我的学习过程。

这是我的代码:

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;
    }
}
}
4

2 回答 2

2

你的代码不完整。您需要实现本教程中描述的其他方法。

本教程很好地描述了蓝牙连接。

您还可以查看PDF 文件。

于 2011-11-29T07:46:46.227 回答
1

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

DiscoveryAgent agent;
agent=local.getdiscoveryagent(discoveryagent.giac,this);
agent.startinquiry(discoveryagent.giac,this);
于 2012-03-28T18:26:34.930 回答