android子线程中弹出Toast

时间:2022-11-01 15:32:30

使用Looper

android子线程中是不能直接弹出Toast,因为子线程中没有Looper,但是我们可以创建一个Looper

Looper.prepare();
Toast.makeText(MainActivity.this, “SOMETHING”, Toast.LENGTH_SHORT).show();
Looper.loop();

使用handler

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private Button button;

// Handler内部类,它的引用在子线程中被使用,发送mesage,被handlerMesage方法接收
private Handler handler = new Handler() {

public void handleMessage(Message msg) {
String str = (String) msg.obj;
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
};
};

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

button = (Button) findViewById(R.id.connect);
button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
new Thread() {
public void run() {
Message msg = new Message();
msg.obj = "Hello";
// 把消息发送到主线程,在主线程里现实Toast
handler.sendMessage(msg);
};
}.start();
}
}