处理程序本身管理消息队列
这可以在Service
.
我做了示例..我将在队列中使用自定义流程...这里可供下载..
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Message msg = h.obtainMessage();
msg.what = 0;
msg.obj = "url1";
h.sendMessage(msg);
Message msg1 = h.obtainMessage();
msg1.what = 1;
msg1.obj = "url2";
h.sendMessage(msg1);
Message msg2 = h.obtainMessage();
msg2.what = 2;
msg2.obj = "url2";
h.sendMessage(msg2);
Message msg3 = h.obtainMessage();
msg3.what = 3;
msg3.obj = "url3";
h.sendMessage(msg3);
}
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e("", "handleMessage(msg) " + msg.what);
download("" + System.currentTimeMillis(), "" + msg.obj);
super.handleMessage(msg);
}
};
private void download(String name, String link) {
try {
// Debug.e("", photo.imagename);
URL url = new URL(link);
HttpGet httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
File outPutFile = new File(
Environment.getExternalStorageDirectory(), name);
OutputStream output = new FileOutputStream(outPutFile);
try {
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
input.close();
}
// Toast.makeText(mContext, "Download completed",
// Toast.LENGTH_SHORT).show();
// incrementCounter(Constant.ACTION_DOWNLOADS, photo.iid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
欢迎其他最佳实践...