我正在寫一個自定義事件,並希望得到一些幫助。我將要談論的大部分內容是基於Custom event listener on Android app提供的幫助在android中創建自定義事件的問題
所以這裏是我的問題。我正在編寫一個應用程序,需要從網絡上下載更新的圖像,將圖像存儲在手機中,然後再顯示這些圖像。基本上,我在啓動畫面中下載任何所需的圖像。然後,當圖像下載並存儲時,啓動畫面將清除,並且任何必要的(新下載的)圖像都會顯示在屏幕上。問題在於:下載過程是通過一個asynctask來完成的,因此圖像加載到屏幕上的部分不能在asynctask中完成。它必須在主UI線程上完成。我想爲主線程創建一個事件和一個自定義事件監聽器來監聽,這基本上告訴主UI線程開始從內存加載下載的圖像是安全的。
根據從上面的鏈接的討論中,我想出了這個迄今爲止...下載收聽interace
public interface DataDownloadListener {
void onDownloadStarted();
void onDownloadFinished();
}
事件類...
public class DataDownloadEvent {
ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public void setOnDownload(DataDownloadListener listener){
this.listeners.add(listener);
}
}
我的問題是我不明白在這些說明中把最後兩步放在哪裏。我認爲我必須將聽衆和事件放在實際啓動下載的類中。但是哪裏?這裏是我的功能啓動下載並保存到設備:
public String download(String sourceLocation) {
String filename = "";
String path = "";
try {
File externalStorageDirectory = Environment
.getExternalStorageDirectory();
URL urlTmp = new URL(sourceLocation);
filename = urlTmp.getFile()
.substring(filename.lastIndexOf("/") + 1);
path = externalStorageDirectory + PATH;
// check if the path exists
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
filename = path + filename;
f = new File(filename);
//only perform the download if the file doesn't already exist
if (!f.exists()) {
Bitmap bitmap = BitmapFactory.decodeStream(urlTmp.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(
filename);
if (bitmap != null) {
bitmap.compress(getFormat(filename), 50, fileOutputStream);
Log.d(TAG, "Saved image " + filename);
return filename;
}
}
else{
Log.d(TAG, "Image already exists: " + filename + " Not re-downloading file.");
}
} catch (MalformedURLException e) {
//bad url
} catch (IOException e) {
//save error
}
return null;
}
而有關注冊聽衆,你在哪裏我把那最後一步?說明書說在初始化期間將其放在某處。這是否意味着我的主要活動的onCreate方法?在主要活動的進口部分的課外?從未做過自定義事件,所以任何幫助將不勝感激。
另外,我知道我可以使用廣播做同樣的事情,但我認爲這可能有點冒失......我認爲正確的做法是創建事件和聽衆... –