共计 1542 个字符,预计需要花费 4 分钟才能阅读完成。
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);
}
}
}
正文完