Bare bones需要消息示例,从AsyncTask到UI线程,不使用Services

时间:2012-06-13 14:31:48

标签: android

我正在寻找简单的示例代码,用于在AsyncTask中设置Message并在UI线程的Handler中处理它。

我见过的示例在服务中处理此问题,而我的应用目前没有使用任何服务。可以在没有服务的情况下使用消息吗?

示例代码将不胜感激!

1 个答案:

答案 0 :(得分:1)

public static final int MSG = 1;
private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

        switch( msg.what ){
            case MSG:{

            }break;
        }
    }
}; 


@Override
public void onCreate(Bundle icicle) {
     super.onCreate(icicle);

     new YourAST(handler).execute();
}


public class YourAST extends AsyncTask<String, Void, Integer> {

    Handler mHandler = null;

    public YourAST(Handler handler){
         this.mHandler = handler;
    } 

    @Override
    protected Integer doInBackground(String... arg) {

        // send message to UIthread
        if(mHandler!=null)
        mHandler.sendEmptyMessage(YourClass.MSG);

        return null;
    }

}