开发者

Android/Java and addEventListeners

I have an Activity class anda RestClient class. Working with Javascript or ActionScript I simple define event listener on the RestClient so the main class can trigger some functions when somet开发者_JAVA技巧hing happens.

Flash example:

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

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

What is the proper way to do it in Android? The main class is the Activity.

Android examples:

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!");
   }
}

Thanks.


An AsyncTask might be the closest thing you're used to for that type of event handling coming from ActionScript. You can subclass the AsyncTask and then define it on your main activity like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜