android-多线程

AsyncTask

public class MyAsyncTask extends AsyncTask<String, Integer, Integer> {
    @Override
    protected void onProgressUpdate(Integer... values) {
        // 更新进度条通知或其它UI元素
        super.onProgressUpdate(values);
    }
    
    @Override
    protected void onPostExecute(Integer result) {
        // 通过UI更新、对话框或通知报告结果
        super.onPostExecute(result);
    }
    
    @Override
    protected Integer doInBackground(String... params) {
        int myProgress = 0;
        // 执行后台处理任务,更新myProgress
        for (int i = 0; i < 10; i++) {
            myProgress++;
            publishProgress(myProgress);
        }
        
        // 返回将传递给onPostExecute
        return myProgress;
    }
}

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //执行一个异步任务
        new MyAsyncTask().execute("inputString1","inputString2");
    }
}

Thread

 

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            
        //执行一个异步任务
        Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background");
        thread.start();
    }
    
    private Runnable doBackgroundThreadProcessing = new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            backgroundThreadProcessing();
        }
    };
    
    private Handler handler = new Handler();
    private void backgroundThreadProcessing() {
        // TODO 在这完成耗时的工作
        
        //将更新从后台发送到用户界面上,方法1:post方法完成返回到主线程
        handler.post(doUpdateGUI);
        
        //方法2:runOnUiThread
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateGUI();
            }
        });
    }
    
    private Runnable doUpdateGUI = new Runnable() {
        public void run() {
            updateGUI();
        };
    };
    
    private void updateGUI() {
        Context context = getApplicationContext();
        String msg = "To health and happiness!";
        int duration = Toast.LENGTH_SHORT;
        
        Toast toast = Toast.makeText(context, msg, duration);
        toast.show();
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。