Android / Java和addEventListeners

时间:2011-06-29 17:25:07

标签: android events event-handling addeventlistener

我有一个Activity类和一个RestClient类。使用Javascript或ActionScript我简单地在RestClient上定义事件监听器,这样主要类可以在发生某些事情时触发一些函数。

Flash示例:

RestClient c = new RestCient()
c.addEventListener(Event.DATA, dataHandler);

function dataHandler(e:Event)
{
 ... do something
}

在Android中执行此操作的正确方法是什么?主要类是Activity。

Android示例:

public class RestClient extends MyConnector 
{
   public RestClient()
   {
      ...   
   }

   protected var onConnect()
   {
      dispatchEvent CONNECT ???
   }

   protected var onClose()
   {
      dispatchEvent CLOSE ???
   }

   ...
}

public class Main extends Activity
{
   RestClient client;

   @Override
   public void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      client = new RestClient();
      client.addEventListener(CONNECT, connectHandler); ?????  
   }

   protected void connectHandler(Event e)
   {
      Log.i("Yeah!", "Connected!");
   }
}

感谢。

1 个答案:

答案 0 :(得分:1)

对于来自ActionScript的此类事件处理,

An AsyncTask可能是您最常用的。您可以继承AsyncTask,然后在主活动上定义它,如下所示:

MyRestTask restTask = new MyRestTask<URL, Integer, Long>() {
 protected Long doInBackground(URL... urls) {
     // instantiate an DefaultHTTPClient and call methods on it here
 }

 protected void onProgressUpdate(Integer... progress) {
     // retrieve progress updates here
 }

 protected void onPostExecute(Long result) {
     // process the response here
 }
}