在我正在开发的Android应用中,我有一个片段,可以启动一个从中获取图像的线程 一个特定的URL,然后在片段中的ImageView上显示该图像。 我遇到的问题是我的应用程序不会等待线程完成,因为我期待。
在AdvertisementFragment.java中:
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Obtain the advertisement controller.
controller = new AdvertisementController();
// Shows a spinner while fetching the advertisement image.
progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.fetchingAdvImage));
controller.showAvertisementImage2();
// Destroy the spinner
progressDialog.dismiss();
return inflater.inflate(R.layout.fragment_advertisement, container, false);
}
控制器有这种方法:
public void showAvertisementImage2() {
GetAdvertisementImageThread advertisementImageThread = new GetAdvertisementImageThread("Advertisement image thread", advertisementData);
try {
advertisementImageThread.t.join();
Log.v("Thread", "Se pone en espera.");
} catch (InterruptedException e) {
Log.v("Thread", "Se llanza la exception.");
e.printStackTrace();
}
}
在GetAdvertisementImageThread类中:
GetAdvertisementImageThread(String threadname,AdvertisementData advertisementDataPassed){ name = threadname; advertisementData = advertisementDataPassed;
advertisementData = new AdvertisementData();
t = new Thread(this, name);
Log.v("Thread", "New thread: " + t);
t.start();
}
public void run() {
try {
// Connect to the url.
in = openHttpConnection(url);
// If the connection was no successful finish the execution.
if (in == null) return;
// Read the InputStream character by character and add it to the pageSourceCode String variable.
InputStreamReader isr = new InputStreamReader(in);
int charRead;
pageSourceCode = "";
char[] inputBuffer = new char[BUFFER_SIZE];
.....
}
}
I was expecting for the Fragment to wait for the Thread to finish but it does not and instead it destroys the
ProgressDialog before the image is fetched and get the image afterwards.
I thought that the .join will make it wait for the Thread to finish but it seems it does not.
What am I doing wrong?
答案 0 :(得分:1)
等待线程完成URL数据获取将是如此lagy,尤其是低速互联网连接。我建议不要等待它完成,让它花时间并显示获取数据的消息;保持用户友好。