2009-08-05 89 views
0

我正在研究J2ME藍牙應用程序,其中一個類搜索其他藍牙設備。它在另一個線程中執行此操作,因此GUI不會凍結。將消息傳遞給Java中的asynchronus工作線程J2ME

我遇到的問題是如何將消息傳遞給線程。我可以要求它搜索或取消搜索,並且它可以告訴GUI找到了其他一些設備。目前我使用通知和等待,但這似乎是一個黑客。我真正想要的是用參數調用notify的某種方式,例如我希望它執行的操作。有沒有辦法做到這一點?

+0

你可以發佈你正在嘗試做的任何代碼片段? – Ram 2009-08-05 08:29:17

回答

2

的一般方法這種情況必須如下:

  1. 解耦數據的遠程源的「查看」。
  2. 確保該視圖能夠在底層數據更改時動態更新。 J2ME組件在默認情況下會這樣做 - 但是如果您創作自己的組件,那麼您必須考慮到這一點。
  3. 運行一個單獨的線程並檢索數據。
  4. 數據到達時通知視圖。

MIDlet的工作代碼下面貼

import javax.microedition.lcdui.Command; 
import javax.microedition.lcdui.CommandListener; 
import javax.microedition.lcdui.Display; 
import javax.microedition.lcdui.Displayable; 
import javax.microedition.lcdui.List; 
import javax.microedition.midlet.*; 


public class AsyncUI extends MIDlet implements SearchListener, CommandListener{ 
    Command CANCEL = new Command("STOP SEARCH",Command.CANCEL,1); 
    Command EXIT = new Command("EXIT",Command.EXIT,2); 
    SearchDevices finder = new SearchDevices(); 
    List deviceList = new List("List of Devices",List.IMPLICIT); 

    public void startApp() { 
     Display d = Display.getDisplay(this); 
     finder.setSearchListener(this); 
     deviceList.addCommand(CANCEL); 
     deviceList.addCommand(EXIT); 
     deviceList.setCommandListener(this); 
     d.setCurrent(deviceList); 
     new Thread(finder).start(); 
    } 

    public void pauseApp() { 
    } 

    public void destroyApp(boolean unconditional) { 
    } 

    public void found(Device d){ 
     deviceList.append(d.getName(), null); 
    } 
    public void commandAction(Command c, Displayable d){ 

     if(c == CANCEL){ 
      finder.cancel(); 
      deviceList.removeCommand(CANCEL); 
     }else if(c== EXIT){ 
      finder.cancel(); /* Cleanup all resources before you quit*/ 
      notifyDestroyed(); 
     } 
    } 
} 

class SearchDevices implements Runnable{ 

    private boolean keepFinding=true; 
    private static final int LONG_TIME=10000; /* 10 Seconds */ 
    SearchListener l =null; /* Currently only one listener. There could be many*/ 

    public void run(){ 
     int i =0; 
     System.out.println(" -- Started the activity of finding --"); 
     while(keepFinding){ 
      try { 
       Thread.currentThread().sleep(LONG_TIME); 
       Device d = new Device("Device Found "+i); 
       i++; 
       System.out.println(" -- Found the device --"); 
       l.found(d); 
      } catch (InterruptedException ex) { 
       ex.printStackTrace(); 
      } 
     } 
     System.out.println(" -- No more devices will be found --"); 
    } 

    public void cancel(){ keepFinding = false; } 
    public void setSearchListener(SearchListener l){this.l=l;} 


} 

    class Device{ 
     String name; 
     public Device(String name){ this.name = name; } 
     public String getName(){ return name ; } 
    } 

    interface SearchListener{ 
     public void found(Device device); 
    } 
1

你必須執行你自己的阻塞隊列,這實際上是一個producer-consumer問題。一旦你有了一個阻塞隊列,你就可以輕鬆地將它們推送到它們自己的方法中的隊列中,讓你覺得你正在對工作線程進行異步調用。