-1

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

我看到的示例在服务中处理此问题,而我的应用程序当前未使用任何服务。可以在没有服务的情况下使用消息吗?

示例代码将不胜感激!

4

1 回答 1

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

}
于 2012-06-13T14:46:44.173 回答