我有一個應用程序具有帶ListView的片段。我ping網絡上的IP地址,當我得到響應時,我將IP地址添加到列表中。一旦我完成了對IP地址的ping操作,我就把這個列表中的IP地址回覆給了我的ping。如何從片段中的後臺線程更新UI
我想要做的就是更新這個ListView,因爲我在ping所有IP地址之後ping而不是做。要ping IP地址,我使用AsyncTask,然後調用Runnable Thread。當我找到IP地址時,如何告訴Fragment從該Runnable類更新UI?
我的課程大致佈局如下。
public class FinderFragment extends ListFragment {
private void CallFind(){
new Find().execute();
}
private class Find extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
SearchNetwork searchNetwork = new SearchNetwork(ipAddress);
try {
searchNetwork.StartFind();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
UpdateDeviceList();
}
}
}
public class SearchNetwork {
public void StartFind() throws InterruptedException {
Thread t[] = new Thread[20];
for(int i=0; i<02; i++){
t[i] = new Thread(new FindDevices(i*5));
t[i].start();
}
for(Thread thread : t){
thread.join();
}
}
class FindDevices implements Runnable{
@Override
public void run() {
//Ping the IP addresses here
//I want to update UI from here
}
}
你試過'getActivity()。runOnUiThread'? –
使用處理程序而不是它請參閱谷歌示例的threadSample示例.http://developer.android.com/training/multiple-threads/communicate-ui.html – mcd