Android 第三十三章 多线程

在子线程中执行耗时的操作,避免阻塞主线程,从而调高运行效率

一、Thread

public class MainActivity extends AppCompatActivity {

    private TextView tv_time;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initThread();
    }

    private void initView() {
        tv_time = findViewById(R.id.tv_time);
    }

    private void initThread() {
        //延时执行
        //方法一
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    mHandler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //方法二
        mHandler.sendEmptyMessageDelayed(0, 2000);


        //子线程跳转到主线程中执行
        new Thread(new Runnable() {
            @Override
            public void run() {
                //方法一
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                //方法二
                mHandler.sendEmptyMessage(0);

                //方法三
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        tv_time.setText("ok");
                    }
                });

                //延迟执行
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_time.setText("yes");
                    }
                }, 1000);

                //方法四
                tv_time.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_time.setText("case");
                    }
                });
            }
        }).start();
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tv_time.setText("测试_" + (count++));
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //避免因activity销毁,handler message 还未执行完毕,导致内存泄漏
        mHandler.removeCallbacksAndMessages(null);
    }
}

二、AsyncTask

/**
 * Params   url     String类型
 * Progress 进度条  Integer
 * Result   返回类型
 */
public class TestAsyncTask extends AsyncTask<String, Integer, byte[]> {

    private Context mContext;
    private ProgressDialog progressDialog;
    private TextView tv_content;

    public TestAsyncTask(Context mContext, TextView tv_content) {
        this.mContext = mContext;
        this.tv_content = tv_content;
    }

    /**
     * 初始化
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在加载数据...");
//        progressDialog.setMax(100);
        progressDialog.show();
    }

    /**
     * 子线程请求网络
     */
    @Override
    protected byte[] doInBackground(String... params) {
        try {
            URL path = new URL(params[0]);
            if (null != path) {
                HttpURLConnection con = (HttpURLConnection) path.openConnection();
                con.setRequestMethod("GET");
                con.setConnectTimeout(3000);
                con.setDoOutput(true);
                con.setDoInput(true);
                con.connect();
                if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = con.getInputStream();
                    ByteArrayOutputStream ops = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    if (inputStream != null) {
                        while ((len = inputStream.read(bytes)) != -1) {
                            ops.write(bytes, 0, len);
                        }

                        return ops.toByteArray();
                    }
                }
            }
        } catch (Exception error) {
            error.printStackTrace();
        }
        return null;
    }

    /**
     * 更新进度条
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
//        progressDialog.setProgress(values[0]);
    }

    /**
     * 更新UI界面
     */
    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        if (bytes == null) {
            tv_content.setText("网络异常,加载数据失败!");
        } else {
            tv_content.setText(new String(bytes));
        }
        progressDialog.dismiss();
    }

}

public class MainActivity extends AppCompatActivity {

    private TextView tv_data;
    private String url = "https://www.baidu.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_data = findViewById(R.id.tv_data);

        new TestAsyncTask(this, tv_data).execute(url);
    }
}

三 、IntentService

/**
 TestIntentService.startActionFirst(this, "this is a", "cat"); TestIntentService.startActionFirst(this, "this is a", "cat");
 
  <service android:name=".TestIntentService" android:exported="true"/>
*/
public class TestIntentService extends IntentService {

    private static final String ACTION_FIRST = "com.example.first.action.First";


    private static final String EXTRA_PARAM1 = "com.example.first.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.example.first.extra.PARAM2";

    public TestIntentService() {
        super("TestIntentService");
    }


    public static void startActionFirst(Context context, String param1, String param2) {
        Intent intent = new Intent(context, TestIntentService.class);
        intent.setAction(ACTION_FIRST);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_FIRST.equals(action)) {
                String param1 = intent.getStringExtra(EXTRA_PARAM1);
                String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFirst(param1, param2);
            }
        }
    }

    private void handleActionFirst(String param1, String param2) {
        Log.d("aaa", param1 + param2);
    }
}

四、HandlerThread

public class MainActivity extends AppCompatActivity {

    HandlerThread mHandlerThread;
    Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandlerThread = new HandlerThread("test");
        mHandlerThread.start();

        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 0:
                        Toast.makeText(MainActivity.this, "测试", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
         };

        mHandler.sendEmptyMessage(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        mHandlerThread.quit();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值