使用几个AsyncTask或HandlerThread(管道线程)有什么好处?

use*_*896 6 java android

HandlerThread在应用程序中有一个用于进行不同时间花费操作的好方法,例如,排序或甚至用于处理Web /文件流?什么更适合用于这样的目的:几个AsyncTask,几个Thread或一个HandlerThreadhttp://hi-android.info/src/android/webkit/WebViewWorker.java.html

Baj*_*Bob 1

简而言之,它们都很好,因为您没有锁定用户界面。

更长的答案,主要取决于偏好。我使用的解决方案是基本线程和处理程序的组合。由于基本线程不在主 UI 线程上运行,因此通常当一个线程完成时,您需要报告或更新设置。这是我使用处理程序和一组易于阅读的键的时候。这样我就可以访问任何视图并根据需要更改它。请记住,声明并保留对视图的全局引用、根据需要分配和使用并在完成后丢弃是不明智的。

private static final int SET_LOADING    = 0;
private static final int SET_TEXT       = 1;


private Handler mEventHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        // if stmts||switch - personal preference
        if(msg.what     == SET_LOADING ){

            setLoading(((Boolean) msg.obj));

        }else if(msg.what == SET_TEXT){

            setText(msg.arg1, (String) msg.obj);

        }
        super.handleMessage(msg);
    }   
}

/**
 * set the text of a textbox
 * @param id int - R.id.{...}
 * @param text String
 */
private void setText(int id, String text){
    TextView t = ((TextView) findViewById(id));
    if(t != null){
        t.setText(text);
    }
}


/**
 * is the UI currently loading something? lock controls
 * @param isLoading boolean
 */
private void setLoading(boolean isLoading){
    mIsLoading = isLoading;
    if(isLoading){
        (SomeSpinningProgressBar).setVisibility(View.VISIBLE);
    }else{
        (SomeSpinningProgressBar).setVisibility(View.INVISIBLE);
    }
}



public void onClick(View v) {
    /**
    * some button that triggers a database connection
    */
    if( v.getId() == R.id.some_button ) {

        /** basic thread */
        new Thread(new Runnable() {
                public void run() { 
                    if(this.hasWebConnection()){
                        /** tell the UI thread to start loading */
                        mEventHandler.sendMessage(
                            mEventHandler.obtainMessage(SET_LOADING, 0, 0, true));

                        // do work...

                        if(someErrorOccuredBoolean){
                            /** report to user of an error */
                            mEventHandler.sendMessage(
                                mEventHandler.obtainMessage(SET_TEXT, R.id.some_textview, 0, "There was an error!"));
                        }
                        /** tell the UI thread to stop loading */
                        mEventHandler.sendMessage(
                                mEventHandler.obtainMessage(SET_LOADING, 0, 0, false));
                    }else{
                        mEventHandler.obtainMessage(SET_TEXT, R.id.some_textview, 0, "No internet found!!"));
                    }
                }
            }
        );      
    }
}
Run Code Online (Sandbox Code Playgroud)