Android客户端单线程下载
具体效果如上图所示,具体操作步骤如:
1、先新建一个工程名为getDataInternet的应用;
2、修改res/values中的string.xml文件,具体代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 4 <string name="app_name">Android客户端单线程下载</string> 5 <string name="hello_world">Hello world!</string> 6 <string name="action_settings">Settings</string> 7 <string name="path">图片路径</string> 8 <string name="getBtnValue">获取图片</string> 9 10 </resources>
3、编写res/Layout中的fragment_main.xml文件,具体代码如下:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="com.example.getdatatointernet.MainActivity$PlaceholderFragment" > 10 11 <LinearLayout 12 android:layout_width="fill_parent" 13 android:layout_height="fill_parent" 14 android:orientation="vertical" 15 > 16 <TextView 17 android:layout_width="fill_parent" 18 android:layout_height="wrap_content" 19 android:text="@string/path" 20 /> 21 <EditText 22 android:layout_width="fill_parent" 23 android:layout_height="wrap_content" 24 android:text="http://b.hiphotos.baidu.com/image/pic/item/1ad5ad6eddc451da70d0dc8db4fd5266d01632b6.jpg" 25 android:id="@+id/path" 26 /> 27 <Button 28 android:layout_width="wrap_content" 29 android:layout_height="wrap_content" 30 android:text="@string/getBtnValue" 31 android:id="@+id/sendBtn" 32 /> 33 <ImageView 34 android:layout_width="wrap_content" 35 android:layout_height="wrap_content" 36 android:id="@+id/imageView" 37 /> 38 </LinearLayout> 39 40 </RelativeLayout>
4、编写NetTool.java类,该类用于操作图片的下载,具体代码如下:
1 package com.example.getdatatointernet; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 8 public class NetTool { 9 10 public static byte[] getImage(String path) throws Exception{ 11 //简历URL路径 12 URL url=new URL(path); 13 14 //得到HttpURLConnection对象 15 HttpURLConnection conn=(HttpURLConnection)url.openConnection(); 16 conn.setRequestMethod("GET");//声明请求方式 17 conn.setConnectTimeout(6*1000);//设置链接超时 18 int a=conn.getResponseCode(); 19 if(conn.getResponseCode()==200) 20 { 21 InputStream iStream=conn.getInputStream();//得到输入流 22 return readInstream(iStream);//返回得到的输入流 23 } 24 25 return null; 26 } 27 28 //读取文件流的内容 29 public static byte[] readInstream(InputStream inputStream) throws Exception{ 30 //创建ByteArrayOutputStream类 31 ByteArrayOutputStream baoStream=new ByteArrayOutputStream(); 32 byte[] buffer=new byte[1024];//声明缓冲区 33 int length=-1;//定义读取默认的长度 34 while((length=inputStream.read(buffer))!=-1){ 35 baoStream.write(buffer,0,length);//把缓冲区中输出到内存中 36 } 37 38 baoStream.close();//关闭输出流 39 inputStream.close();//关闭输入流 40 return baoStream.toByteArray();//返回输出流的字节数组 41 } 42 }
5、编写核心代码MainActivity.java类,具体代码如下:
1 package com.example.getdatatointernet; 2 3 import android.annotation.SuppressLint; 4 import android.graphics.Bitmap; 5 import android.graphics.BitmapFactory; 6 import android.os.Bundle; 7 import android.os.StrictMode; 8 import android.support.v4.app.Fragment; 9 import android.support.v7.app.ActionBarActivity; 10 import android.util.Log; 11 import android.view.LayoutInflater; 12 import android.view.Menu; 13 import android.view.MenuItem; 14 import android.view.View; 15 import android.view.ViewGroup; 16 import android.widget.Button; 17 import android.widget.EditText; 18 import android.widget.ImageView; 19 import android.widget.Toast; 20 21 @SuppressLint("ValidFragment") 22 public class MainActivity extends ActionBarActivity { 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 29 if (savedInstanceState == null) { 30 getSupportFragmentManager().beginTransaction() 31 .add(R.id.container, new PlaceholderFragment()).commit(); 32 } 33 } 34 35 @Override 36 public boolean onCreateOptionsMenu(Menu menu) { 37 38 // Inflate the menu; this adds items to the action bar if it is present. 39 getMenuInflater().inflate(R.menu.main, menu); 40 return true; 41 } 42 43 @Override 44 public boolean onOptionsItemSelected(MenuItem item) { 45 // Handle action bar item clicks here. The action bar will 46 // automatically handle clicks on the Home/Up button, so long 47 // as you specify a parent activity in AndroidManifest.xml. 48 int id = item.getItemId(); 49 if (id == R.id.action_settings) { 50 return true; 51 } 52 return super.onOptionsItemSelected(item); 53 } 54 55 /** 56 * A placeholder fragment containing a simple view. 57 */ 58 public class PlaceholderFragment extends Fragment { 59 60 public PlaceholderFragment() { 61 } 62 63 @Override 64 public View onCreateView(LayoutInflater inflater, ViewGroup container, 65 Bundle savedInstanceState) { 66 View rootView = inflater.inflate(R.layout.fragment_main, container, 67 false); 68 69 StrictMode.setThreadPolicy(new 70 StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); 71 StrictMode.setVmPolicy( 72 new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); 73 74 final EditText imageText=(EditText)rootView.findViewById(R.id.path); 75 final ImageView imageView=(ImageView)rootView.findViewById(R.id.imageView); 76 final Button btn=(Button)rootView.findViewById(R.id.sendBtn); 77 78 btn.setOnClickListener(new View.OnClickListener() { 79 80 @Override 81 public void onClick(View v) { 82 // TODO Auto-generated method stub 83 String path=imageText.getText().toString(); 84 try 85 { 86 byte[]data=NetTool.getImage(path); 87 Bitmap bm=BitmapFactory.decodeByteArray(data, 0, data.length); 88 imageView.setImageBitmap(bm); 89 }catch(Exception e) 90 { 91 Log.i("MyTest",e.getMessage()); 92 Toast.makeText(MainActivity.this, e.getMessage(), 1).show(); 93 } 94 } 95 }); 96 return rootView; 97 } 98 } 99 100 }
6、在AndroidManifest.xml中添加服务权限
<uses-permission android:name="android.permission.INTERNET"/>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。