我有一个Activity类和RestClient类。使用Javascript或ActionScript,我在RestClient上简单地定义了事件侦听器,这样主类就可以在发生某些事情时触发一些函数。
Flash示例:
RestClient c = new RestCient()
c.addEventListener(Event.DATA, dataHandler);
function dataHandler(e:Event)
{
... do something
}
在安卓系统中,正确的方法是什么?主要类是"活动"。
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!");
}
}
谢谢。
AsyncTask可能是您最习惯的来自ActionScript的事件处理类型。您可以对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
}
}