,你可以用它代替的AsyncTask HandlerThread,
public class TestActivity extends Activity implements OnClickListener {
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private static final int BACKGROUND_TASK_WORK_SLOWER = 0;
private static final int BACKGROUND_TASK_WORK_FASTER = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_content);
Button btnWorkSlower = (Button) findViewById(R.id.work_slower);
btnWorkSlower.setOnClickListener(this);
Button btnFaster = (Button) findViewById(R.id.work_faster);
btnFaster.setOnClickListener(this);
mBackgroundThread = new HandlerThread("ConstructionWorker",
Process.THREAD_PRIORITY_BACKGROUND);
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
performBackgroundTask(msg.what, msg.obj);
}
};
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.work_slower:
scheduleBackgroundTask(BACKGROUND_TASK_WORK_SLOWER);
break;
case R.id.work_faster:
scheduleBackgroundTask(BACKGROUND_TASK_WORK_FASTER);
break;
default:
break;
}
}
protected void scheduleBackgroundTask(int task) {
mBackgroundHandler.sendEmptyMessage(task);
}
protected void performBackgroundTask(int task, Object arg) {
switch (task) {
case BACKGROUND_TASK_WORK_SLOWER: {
// work slower here
break;
}
case BACKGROUND_TASK_WORK_FASTER: {
// work faster here
break;
}
}
}
}
這看起來不錯。問題 - 建築工人線程如何溝通進度? – user1532208 2013-03-08 12:59:28