运行效果

Android studio 简单的多线程_第1张图片

文件结构

Android studio 简单的多线程_第2张图片

主要代码

MainActivity

package cn.edu.sicnu.threaddemo;import android.os.AsyncTask;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ProgressBar;import android.widget.TextView;import java.lang.ref.WeakReference;import java.security.PublicKey;public class MainActivity extends AppCompatActivity {    private static final String TAG = "MainActivity";    TextView textView;    ProgressBar progressBar;    MyAsyncTask myAsyncTask;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = findViewById(R.id.textView);        progressBar = findViewById(R.id.progressBar);    }    static class MyAsyncTask extends AsyncTask{        WeakReference weakReference;        public MyAsyncTask(MainActivity activity){            weakReference = new WeakReference(activity);        }        @Override        protected void onPreExecute() {            super.onPreExecute();            MainActivity activity = weakReference.get();            if (activity!=null) activity.progressBar.setProgress(0);            Log.d(TAG, "onPreExecute: ");        }        @Override        protected Integer doInBackground(Integer... integers) {            int sum = 0;            for(int i = 1; i < 100; i++) {                try {                    Log.d(TAG, "doInBackground: " + Thread.currentThread().getName());                    Thread.sleep(100);                } catch (InterruptedException e) {                    e.printStackTrace();                }                sum += i;                publishProgress(i);                if(isCancelled()) break;            }           return -1;        }        @Override        protected void onProgressUpdate(Integer... values) {            super.onProgressUpdate(values);            Log.d(TAG, "onProgressUpdate: ");            MainActivity activity = weakReference.get();            if (activity!=null) {                activity.textView.setText("progress"+values[0]);                activity.progressBar.setProgress(values[0]);            }        }        @Override        protected void onCancelled() {            super.onCancelled();            MainActivity activity = weakReference.get();            if (activity!=null) activity.textView.setText("cancel!!!!");        }        @Override        protected void onPostExecute(Integer integer) {            super.onPostExecute(integer);            Log.d(TAG, "onPostExecute: ");            MainActivity activity = weakReference.get();            if (activity!=null) {                activity.textView.setText("congratulation!!!finished");                activity.progressBar.setProgress(0);            }        }    }    public void calculate(View v) {        myAsyncTask = new MyAsyncTask(this);        myAsyncTask.execute(0);    }    public void stop(View v){        myAsyncTask.cancel(true);    }//    private MyHandler handler = new MyHandler(this);//    private Handler handler = new Handler() {//        @Override//        public void handleMessage(Message msg) {//            super.handleMessage(msg);////            switch (msg.what){//                case 0://                    textView.setText("progress:"+msg.arg1);////                    break;//                case 1://                    textView.setText("congratulation!!!finished"+msg.what);////                    break;//            }//            Log.d(TAG, "handleMessage: "+Thread.currentThread().getName());//        }//    };////    static class MyHandler extends Handler{////        WeakReference weakReference;////        public MyHandler(MainActivity activity){//            this.weakReference = new WeakReference(activity);//        }//////        @Override//        public void handleMessage(Message msg) {//            super.handleMessage(msg);////            MainActivity activity = weakReference.get();//            if (activity == null) return;;////            switch (msg.what){//                case 0://                    activity.textView.setText("progress:"+msg.arg1);////                    break;//                case 1://                    activity.textView.setText("congratulation!!!finished"+msg.what);////                    break;//            }//            Log.d(TAG, "handleMessage: "+Thread.currentThread().getName());//        }//    }////        new Thread(new Runnable() {//            @Override//            public void run() {//                int sum = 0;//                for(int i = 1; i < 100; i++){//                    try {//                        Log.d(TAG, "run: "+Thread.currentThread().getName());//                        Thread.sleep(100);//                    } catch (InterruptedException e) {//                        e.printStackTrace();//                    }//                    sum += i;//                    final int j = i;//                    handler.post(new Runnable() {//                        @Override//                        public void run() {//                            textView.setText("progress:"+j);//                        }//                    });////                    Message msg = handler.obtainMessage();////                    msg.what = 0;////                    msg.arg1 = i;////                    handler.sendMessage(msg);//                }////                handler.post(new Runnable() {//                    @Override//                    public void run() {//                        textView.setText("congratulation!!!finished");//                    }//                });////////                Message msg = handler.obtainMessage();////                msg.what = 1;////                handler.sendMessage(msg);//            }//        }).start();////////    }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="cn.edu.sicnu.threaddemo.MainActivity"    tools:layout_editor_absoluteY="81dp">    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginBottom="26dp"        android:text="Hello World!"        app:layout_constraintBottom_toTopOf="@+id/button2"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent" />    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginBottom="27dp"        android:layout_marginEnd="53dp"        android:onClick="calculate"        android:text="start"        app:layout_constraintBottom_toTopOf="@+id/progressBar"        app:layout_constraintEnd_toEndOf="@+id/textView" />    <ProgressBar        android:id="@+id/progressBar"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="0dp"        android:layout_height="40dp"        android:layout_marginBottom="105dp"        android:layout_marginEnd="11dp"        android:layout_marginStart="11dp"        android:max="100"        android:progress="0"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent" />    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginEnd="66dp"        android:layout_marginStart="64dp"        android:onClick="stop"        android:text="stop"        app:layout_constraintBaseline_toBaselineOf="@+id/button"        app:layout_constraintEnd_toEndOf="@+id/progressBar"        app:layout_constraintStart_toStartOf="@+id/textView" />android.support.constraint.ConstraintLayout>

更多相关文章

  1. Android 6.0 源代码编译实践
  2. android控制home键 代码
  3. Android之常用功能代码
  4. android客户端加密代码
  5. Android如何通过代码将res里的图片转换成drawable.
  6. Android引入外部字体源代码
  7. Android Activity 启动/退出 动画效果
  8. 【Android】Activity遮罩效果的实现
  9. Android APP 版本更新通知代码

随机推荐

  1. Android开发中各个版本的问题总结
  2. 简单音乐播放实例的实现,Android(安卓)Se
  3. 学习android笔记1 之工具篇
  4. Android:自定义View实现随滑动由箭头变对
  5. android 编译java.util.zip.ZipException
  6. Android编程开发实现带进度条和百分比的
  7. Android(安卓)框架启动流程
  8. android 关掉Eclipse的自动代码提示
  9. H5-input 弹起键盘遮盖输入框(Android),
  10. SpyEye on Android