as報錯1:

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

在Android中不允許Activity裏新啓動的線程訪問該Activity裏的UI組件,這樣會導致新啓動的線程無法改變UI組件的屬性值。

在很多時候都需要異步獲取數據刷新UI控件,這時候採取的方法就是Handler消息機制和AsyncTask異步任務兩種解決方法。

方法一、new Thread() {

public void run() {

Log.i("log", "run");

Looper.prepare();

Toast.makeText(ActivityTestActivity.this, "toast", 1).show();

Looper.loop();// 進入loop中的循環,查看消息隊列

};

}.start();

方法二、post給主線程處理

mainHandler.post(new Runnable()
{

@Override
public void run()
{

if (toast == null)
{ toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); }
toast.setText(msg);

toast.setDuration(Toast.LENGTH_SHORT); toast.show();

} });



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章