android开发之Handler

Handler实例

子类需要继承Hendler类,并重写handleMessage(Message msg) 方法,用于接受线程数据,主要看具体实例,重要的部分都已给了注释:


public class MainActivity extends Activity {

/** Called when the activity is first created. */  
private WebView wv =null;  
private Handler h = new Handler();  
public final String TAG = "UNISDP";  
public final String MY_LOG = "my_log";   
MyHandler myHandler;   
   
public void onCreate(Bundle savedInstanceState)   
{  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  
    wv = (WebView) findViewById(R.id.web);  
    WebSettings webSettings = wv.getSettings();  

    webSettings.setJavaScriptEnabled(true);  
    webSettings.setSaveFormData(false);  
    webSettings.setSavePassword(false);  
    webSettings.setSupportZoom(false);  
    wv.addJavascriptInterface(new runJavaScript(), "myjs");  
    wv.loadUrl(sdFilePath);  
      
    myHandler = new MyHandler(); // 当创建一个新的Handler实例时, 它会绑定到当前线程的消息队列中,开始分发数据  
      
    MyThread m = new MyThread();  
    Thread getDataFromServer_thread = new Thread(m);  
    getDataFromServer_thread.start();     
}  

取数据线程 从页游服务器获取数据


class MyThread implements Runnable   
{   
    public void run()   
    {     
        Message msg ;  
        Bundle b ;                                
        while(true)  
        {  
            try   
            {  
                Thread.sleep(1000);  
                msg = new Message();  
                b = new Bundle();// 存放数据  
                b.putString("value", "发送给UI线程的数据...");  
                msg.setData(b);  
                MainActivity.thiswww.sangpi.commyHandler.sendMessage(msg); // 向Handler发送消息,更新UI  
            }   
            catch (InterruptedException e)   
            {  
                e.printStackTrace();  
            }                     
               
        }  
    }   
}    
// 接受消息,处理消息 ,此Handler会与当前主线程一块运行   
class MyHandler extends Handler  
{   
    public MyHandler()   
    {   
    }   
    public MyHandler(Looper L)  
    {  
        super(L);  
    }   
    // 子类必须重写此方法,接受数据   
    @Override   
    public void handleMessage(Message msg)   
    {        
        super.handleMessage(msg);          
        // 此处可以更新UI   
        Bundle b = msg.getData();   
        String strValue = b.getString("value");   
        //MainActivity.this.button.append(color);   
        Log.i(MY_LOG,strValue);  
    }   
}     

}

android开发之Handler

上一篇:iOS自动化遇到坑的解决方式


下一篇:Qt调用DLL