我有一个按钮的主要活动,在点击方法中,我正在设置一个DownloadManager类,它创建一个线程池,使用多个线程从给定的URL下载视频。
问题是,如何将每个线程的状态发布到UI editText对象?
我在我的DownloadManager类中使用Handler,它实例化并行运行的线程。
以下是点击代码上的MainActivity按钮:
public void buttonClick(View view) {
EditText eText1 = (EditText) findViewById(R.id.editText); //URL input text box
EditText eText = (EditText) findViewById(R.id.editText2); //output text box
new DownloadManager(eText1.getText().toString(), this.getFilesDir()).runDownloadThreadPool();
以下是DownloadManager构造函数:
public DownloadManager(String url, File f) {
this.url1 = url;
this.f = f;
sDM = this;
mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message inputMessage){
DownloaderThreadPool t = (DownloaderThreadPool) inputMessage.obj;
//Toast.makeText(android.os.Environment.getApplicationContext(), t.threadMessage, Toast.LENGTH_LONG);
}
};
}
如何将第一个代码中的eText对象传递给DownloadManager,以便在handleMessage覆盖函数中更新?
答案 0 :(得分:2)
只需将其作为另一个参数添加到构造函数中。
public DownloadManager(EditText outputUI, String url, File f) {
this.outputUI = outputUI;
...
mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message inputMessage){
DownloaderThreadPool t = (DownloaderThreadPool) inputMessage.obj;
outputUI.setText(t.threadMessage);
}
};
}
答案 1 :(得分:1)
您可以通过构造函数传递它:
public DownloadManager(String url, File f, EditText editText) {
this.url1 = url;
this.f = f;
sDM = this;
mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message inputMessage){
DownloaderThreadPool t = (DownloaderThreadPool) inputMessage.obj;
//Toast.makeText(android.os.Environment.getApplicationContext(), t.threadMessage, Toast.LENGTH_LONG);
editText.setText("Some text");
}
};
}
然后在实例化DownloadManager类时传入它:
new DownloadManager(eText1.getText().toString(), this.getFilesDir(), eText).runDownloadThreadPool();
答案 2 :(得分:0)
1:通过构造函数将EditText的实例传递给DownloadManager,如上所述; 2:通过回调。如下:
首先,定义一个回调:
public interface OnStatusChangedListener {
public void onStatusChanged(int status);
}
然后实现OnStatusChangedListener接口:
OnStatusChangedListener mListener = new OnStatusChangedListener() {
@Override
public void onStatusChanged(int status) {
//editText.setText(String.valueOf(status));
}
};
public DownloadManager(String url, File f, final OnStatusChangedListener listener) {
this.url1 = url;
this.f = f;
sDM = this;
mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message inputMessage){
DownloaderThreadPool t = (DownloaderThreadPool) inputMessage.obj;
//listener.onStatusChanged(status);
}
};
}
最后,在实例化DownloadManager类时传递mListener:
new DownloadManager(eText1.getText().toString(), this.getFilesDir(), mListener).runDownloadThreadPool();