2013-03-06 60 views
0

我正在嘗試創建一個Thread並使用Hander來顯示Toast消息。Thread for android

當我運行該程序時,模擬器不顯示任何東西!

我對線程完全陌生。

請幫我解決這個:)

package com.example.android_thread_hu; 

import android.os.Bundle; 
import android.os.Handler; 
import android.app.Activity; 
import android.view.Menu; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

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

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu);  
     return true; 
    } 

    Thread thread = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      handler.handleMessage(null) ; 
     } 
    }); 

    public Handler handler = new Handler(){  
     public void handleMessage() { 
      Toast.makeText(
        MainActivity.this, 
        "finish!!!!", 
        Toast.LENGTH_SHORT).show(); 
     } 
    }; 
} 
+0

以這種方式使用'Thread'的目的是什麼,除了明顯的顯示'Toast'可以做得更簡單嗎? – codeMagic 2013-03-06 02:48:15

回答

1

試圖聲明你的線程,如:

Thread thread = new Thread(new Runnable() { 
    @Override 
    public void run() { 
     handler.sendEmptyMessage() ; 
    } 
}); 

此外,還要確保Toast.LENGTH_SHORT是不是太短,該消息被衰減太快

0

我覺得線程太複雜了

package com.example.android_thread_hu; 

import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.app.Activity; 
import android.view.Menu; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

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

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 

    return true; 
    } 
    Thread thread=new Thread(new Runnable() 
          { Message message; 
    String obj="run"; 
    @Override 
    public void run() 
    { 
     message = handler.obtainMessage(1,obj); 
     handler.sendMessage(message); 
    } 
    }); 

    public Handler handler = new Handler(){ 
    @Override 
    public void handleMessage(Message msg) { 
     super.handleMessage(msg); 
     String MsgString = (String)msg.obj; 
     if (MsgString.equals("run")) 
     { 
     //do something 

     Toast.makeText(MainActivity.this,"finish!!!!",Toast.LENGTH_SHORT).show(); 


     } 

    } 
    }; 
}