3分钟
7.7 实训步骤
实训步骤
\1. 制作程序主界面布局,包括输入图片网址的EditText组件、访问按钮Button和图片显示组件Image View。
\2. 在清单文件中添加网络访问权限。
<uses-permission android:name="android.permission.INTERNET"/>
\3. 在MainActivity中编写与界面交互的代码,将服务器返回的图片显示在界面上。
public class MainActivity extends AppCompatActivity {
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView ivPic;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == CHANGE_UI) {
Bitmap bitmap = (Bitmap) msg.obj;
ivPic.setImageBitmap(bitmap);
} else if (msg.what == ERROR) {
Toast.makeText(MainActivity.this, "显示图片错误",
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
ivPic = (ImageView) findViewById(R.id.iv_pic);
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_SHORT).show();
} else {
new Thread() {
private HttpURLConnection conn;
private Bitmap bitmap;
public void run() {
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
Message msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
conn.disconnect();
}
}.start();
}
}
}\4. 运行程序查看运行结果。
学员评价