public interface DownloadListener {
public void onDownloaded();
}
public class DownloadManager {
private static DownloadManager instance;
private DownloadListener mDownloadListener;
public static synchronized DownloadManager getInstance(){
if(instance == null)
instance = new DownloadManager();
return instance;
}
private DownloadManager() {
myHandler.sendEmptyMessageDelayed(29, 3 * 1000);
}
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}
Handler myHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == 29) {
mDownloadListener.onDownloaded();
return true;
}
return false;
}
});
}
public class I implements DownloadListener {
public I() {
DownloadManager.getInstance().registerDownloadListener(this);
}
@Override
public void onDownloaded() {
Log.e("TAG", "I onDownloaded");
}
}
public class You implements DownloadListener {
public You() {
DownloadManager.getInstance().registerDownloadListener(this);
}
@Override
public void onDownloaded() {
Log.e("TAG", "You onDownloaded");
}
}
public class PATTERNSActivity extends Activity implements DownloadListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new I();
new You();
DownloadManager.getInstance().registerDownloadListener(this);
}
@Override
public void onDownloaded() {
Log.e("TAG","PATTERNSActivity onDownloaded");
}
}
我期待着得到:爲什麼我的聽衆沒有註冊?
我onDownloaded
您onDownloaded
PATTERNSActivity onDownloaded
但我只得到:
PATTERNSActivity onDownloaded
這是什麼問題?
我知道,如果我創建3個不同的DowmloadManager的每3個對象正在偵聽下載狀態 - 一切正常。但我想只有一個DownloadManager。有沒有可能? – drifter 2012-01-04 19:36:49
@drifter當然;通過將每個監聽器保存在列表中來註冊。在處理程序中迭代列表,調用每個監聽器的'onDownloaded'。請參閱編輯。 – 2012-01-04 19:38:44
所以我需要使用觀察者模式和聽衆列表來解決這個問題。這只是這種目的的方法嗎? – drifter 2012-01-04 19:42:18