2011-11-29 32 views
0

我是J2ME的新手。我正在學習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; 
    } 
} 
} 

回答

2

你的代碼是不完整的。您需要執行tutorial中描述的其他方法。

本教程非常好地描述了藍牙連接。

您還可以查看this PDF文件。

+0

無論我找到了藍牙應用此最少的代碼。它再次在模擬器中工作正常。當我在手機中運行時遇到問題。所以我認爲還有其他一些問題。 http://j2mesamples.blogspot.com/2009/02/how-to-find-active-bluetooth-devices.html – Gourav

1

你必須在你的代碼像添加DiscoveryAgent

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