case 1:
runInFrontendProgress(msg.arg1);
break;
}
}
};
...
final protected void publishProgress(int progress) { // added
handler.obtainMessage(1, progress, 0);
}
protected void runInFrontendProgress(int progress) { // added
}
}
public class MainActivity extends Activity {
...
class SubHandlerAndThread extends HandlerAndThread {
@Override
protected void runInBackend(String url) {
System.out.println("Start download from url:" + url);
for (int i = 0; i < 10; ++i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrack();
}
publishProgress(i*10); // added
}
}
...
@Override
protected void runInFrontendProgress(int progress) { // added
System.out.println("Progress: " + progress);
}
}
}
你可能已经没有耐心一版一版的进化了,那我就跳跃一下吧,一次多加几条需要:一、我们下载完了可能要得到文件的路径,所以我们给runInFrontend方法加一个输入参数filePath表示路径;二、把子类必须实现的方法改成抽象方法,类也改成抽象方法;我把代码中的一些方法名改一下,使其更好理解,把doInBackground改为execute,把runInFrontend改为onPostExecute,把runInFrontendProgress改为onProgressUpdate。最终版如下:
public abstract class HandlerAndThread {
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
onPostExecute((String) msg.obj);
break;
case 1:
onProgressUpdate(msg.arg1);
break;
}
}
};
public void doInBackground(final String url) {
new Thread() {
public void run() {
String result = runInBackend(url);
handler.obtainMessage(0, result);
}
};
}
final protected void publishProgress(int progress) {
handler.obtainMessage(1, progress, 0);
}
abstract protected String runInBackend(String url);
protected void onPostExecute(String filePath) { }
protected void onProgressUpdate(int progress) { }
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "";
new SubHandlerAndThread().doInBackground(url);
}
class SubHandlerAndThread extends HandlerAndThread {
@Override
protected String runInBackend(String url) {
System.out.println("Start download from url:" + url);
for (int i = 0; i < 10; ++i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i*10);
}
return "/path/to/file";
}
@Override
protected void onPostExecute(String filePath) {
System.out.println("Download finished");
}
@Override
protected void onProgressUpdate(int progress) {
System.out.println("Progress: " + progress);
}
}
}