简体   繁体   中英

Solve This J2ME Bluetooth Exception

I am new to J2ME. I am learning J2ME Bluetooth application development. I have written some simple code to get the name of my local Bluetooth device. It is working fine in the emulator. But when I try it in my phone then it throws following error.

  1. If Bluetooth in my phone is off, then it throws: javax.bluetooth.BlueToothStateException .
  2. If Bluetooth in my phone is on, then it throws: javax.bluetooth.bluetoothstateexception: initialize - GetProperty failed

Please help me to get rid of this error, so that I can move forward with my learning process.

Here is my code:

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

you code is incomplete. you need to implement the other methods as described in this tutorial .

This tutorial describes Bluetooth Connection very well.

You can Also look at this PDF file.

You have to add DiscoveryAgent in your code like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM