packagecom.example.jinwei.test;
importandroid.app.ProgressDialog;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ImageView;
importandroid.widget.TextView;
importandroid.widget.Toast;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
public classMainActivityextendsAppCompatActivityimplementsView.OnClickListener {
private static final intMSG_SUCC=1;
private static final intMSG_ERROR=2;
private static final intMSG_EXCEPTION=3;
finalStringTAG="TEST";
privateButtonbtn_start;
privateTextViewtextview_desc;
privateImageViewimg_desc;
privateEditTextedit_imgUrl;
privateInputStreamis;
privateStringimg_path="";
privateProgressDialogdialog;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview_desc= (TextView) findViewById(R.id.textview_desc);
img_desc= (ImageView) findViewById(R.id.img_desc);
edit_imgUrl= (EditText) findViewById(R.id.edit_imgUrl);
dialog=newProgressDialog(this);
dialog.setTitle("Alert");
dialog.setMessage("Downloading...");
dialog.setCancelable(false);
btn_start= (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
btn_start.setText("启动另一个Activity");
}
privateHandlerhandler=newHandler(){
@Override
public voidhandleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
caseMSG_SUCC:
Bitmap bitmap = (Bitmap) msg.obj;
img_desc.setImageBitmap(bitmap);
dialog.hide();
break;
caseMSG_ERROR:
Toast.makeText(MainActivity.this,"Success!",Toast.LENGTH_LONG).show();
break;
caseMSG_EXCEPTION:break;
}
}
};
@Override
public voidonClick(View view) {
dialog.show();
img_path=edit_imgUrl.getText().toString();
Toast.makeText(this,img_path,Toast.LENGTH_LONG).show();
newThread(newRunnable() {
@Override
public voidrun() {
try{
URL url =newURL(img_path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
intcode = conn.getResponseCode();
if(code ==200){
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
Message msg =newMessage();
msg.obj= bitmap;
msg.what=MSG_SUCC;
handler.sendMessage(msg);
}else{
Message msg =newMessage();
msg.what=MSG_ERROR;
handler.sendMessage(msg);
}
}catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
protected voidonActivityResult(intrequestCode,intresultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
相关文章:http://www.jianshu.com/p/adcc1740686d
Android多线程相关文章:http://lavasoft.blog.51cto.com/62575/27069/