阅读 618

Android多线程之间通讯

因为工作需要所以在通过手机和PC之间进行蓝牙通讯,因为IO过程不能在主线程中进行所以就使用了多线程,编写代码时遇到了一些小坑,记录一下。

Handler + Message 方式进行多线程通讯

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button btn1;

    private Handler mHandler;

    private void init() {
        btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    downFile();
                    Log.d("debug", "阻塞么?");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

    private void downFile() throws InterruptedException {
        mHandler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: Toast.makeText(getApplicationContext(), "把音量开到最大",
                            Toast.LENGTH_SHORT).show();
                    break;
                    case 2: Toast.makeText(getApplicationContext(), " 有话对你讲",
                            Toast.LENGTH_SHORT).show();
                        break;
                    default:Toast.makeText(getApplicationContext(), "什么鬼",
                            Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
            }
        }.start();
    }
}
复制代码
文章分类
前端
文章标签