我正在制作一个简化的应用程序,只有一个EditText,用户输入URL地址和按钮“下载”。当用户点击按钮时,应用程序应下载给定网站的来源并将其打印在屏幕上。我该怎么做?或者我应该从哪里开始寻找解决方案?
答案 0 :(得分:0)
首先在您的Manifest文件中为INTERNET提供权限
<uses-permission android:name="android.permission.INTERNET" />
这是你的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_url"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="bottom">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android:layout_width="233dp"
android:layout_height="58dp"
android:text="New Button"
android:id="@+id/downloadImage"
android:layout_gravity="center"
android:background="@color/blue"
android:clickable="true" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="145dp"
android:layout_height="58dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView786" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="45dp">
</LinearLayout>
</LinearLayout>
这是您的活动
public class Download extends Activity {
Button bt;
ImageView iv;
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
bt = (Button)findViewById(R.id.downloadImage);
et = (EditText )findViewById(R.id.et_url);
iv = (ImageView)findViewById(R.id.imageView786);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DownloadImageFromPath(et.getText().toString());
}
});
}
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
//ImageView iv = (ImageView)findViewById(R.id.imageView786);
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}
}
catch(Exception ex){
Log.e("Exception", ex.toString());
}
}
现在,如果您将在编辑文本中提供网址 http://i.imgur.com/bIRGzVO.jpg它会显示图片