建立在AsyncTask
這樣,你的工作不會過載主線程的位圖:
private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
protected void onPreExecute() {
// Runs on the UI thread before doInBackground
// Good for toggling visibility of a progress indicator
progressBar.setVisibility(ProgressBar.VISIBLE);
}
protected Bitmap doInBackground(String... strings) {
// Some long-running task like downloading an image.
Bitmap = downloadImageFromUrl(strings[0]);
return someBitmap;
}
protected void onProgressUpdate(Progress... values) {
// Executes whenever publishProgress is called from doInBackground
// Used to update the progress indicator
progressBar.setProgress(values[0]);
}
protected void onPostExecute(Bitmap result) {
// This method is executed in the UIThread
// with access to the result of the long running task
imageView.setImageBitmap(result);
// Hide the progress bar
progressBar.setVisibility(ProgressBar.INVISIBLE);
}
}
而當你需要在MAINT線程運行的東西再次使用這樣的:
MyActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//Your code to run in GUI thread here
}//public void run() {
});
謝謝,我會試試這個。 –
我嘗試了很多次,但是卻出錯。因爲從紋理視圖獲取位圖應該在UI線程中執行。那麼還有其他方法可以嘗試嗎?我希望它是....感謝 –
在調用異步任務之前獲取位圖,然後在該任務中執行繁重的工作。這解決了你的問題? – GuilhermeFGL