private void doHardWork() {
runInBackend(); //added
}
};
}
//added
protected void runInBackend() {
}
//added
protected void runInFrontend() {
}
}
一个可复用的类就出炉了,我们写一个子类,并用一个Activity来调用一下吧:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new SubHandlerAndThread().doInBackground();
}
class SubHandlerAndThread extends HandlerAndThread {
protected void runInBackend() {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void runInFrontend() {
System.out.println("Task has been done");
}
}
}
这样是不是比直接写Thread和Handler简洁了许多呢,这里我是用sleep来模似长时间事务的,如果在真实的环境中,我们可能是要下载,如果是下载,我们可能希望传入个下载地址的参数到后台线程,来让他按我们的需要下载,我们给加doInBackground方法加一个参数,于是HandlerAndThread类的代码就变成这样:
public class HandlerAndThread {
...
public void doInBackground(final String url) { // added url
new Thread() {
public void run() {
doHardWork();
handler.sendEmptyMessage(0);
}
private void doHardWork() {
runInBackend(url); // added url
}
};
}
protected void runInBackend(String url) { // added url
}
...
}
而调用类的代码变成这样:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "";
new SubHandlerAndThread().doInBackground(url); //added url
}
class SubHandlerAndThread extends HandlerAndThread {
@Override
protected void runInBackend(String url) { // added url
System.out.println("Start download from url:" + url);
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void runInFrontend() {
System.out.println("finish download");
}
}
}
假如是下一个文件呢,我们是不是加一个进度更新的方法呢,于是又变成这样:
public class HandlerAndThread {
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) { // added
case 0:
runInFrontend();
break;