首页 > 代码库 > 后台进程弹Toast的几种方案

后台进程弹Toast的几种方案

在后台进程弹Toast,使用方案有:由UI线程传入一个Activity參数、View參数或者Handler參数,使用Activity.runOnUiThread(Runnable)View.post(Runnable)或者Handler.sendMessage()的方法。

这样做有可能引发内存泄露。避免内存泄露的方案,使用Handler.post()和Handler.obtainMessage().sendToTarget():

<script type="text/javascript" src="https://code.csdn.net/snippets/312372.js"></script><link rel="stylesheet" type="text/css" href="https://code.csdn.net/assets/embed-6889884a60106e973f6b1feb9c0a9986.css" media="screen">
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
new Thread(){
@Override
public void run(){
// Looper.prepare();
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"test1",Toast.LENGTH_SHORT).show();
}
});
}
}.start();

new Thread(){
@Override
public void run(){
// Looper.prepare();
new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg){
Toast.makeText(getApplicationContext(),"test2",Toast.LENGTH_SHORT).show();
}
}.obtainMessage().sendToTarget();
}
}.start();
来自CODE的代码片
snippet_file_0.txt