xpepermint
xpepermint

Reputation: 36243

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 something 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.

Upvotes: 0

Views: 205

Answers (1)

citizen conn
citizen conn

Reputation: 15390

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

Upvotes: 1

Related Questions