Android 多线程下载 从自己搭建的本地服务器下载图片实例

来源:互联网 发布:方阵和矩阵的区别 编辑:程序博客网 时间:2024/06/05 11:04

   关于如何从自己在本地搭载的服务器下载图片实例

创建一个web项目,并在该项目上存入一张图片zxy.jpg ,然后将该项目运行在本地服务器;这一部分属于javaee的基础知识,不进行赘述。



创建类DownLoad.java

  

public class DownLoad  {    private Handler mhandler;    public DownLoad(Handler handler){        this.mhandler=handler;    }    //创建固定的线程池    private Executor threadPool= Executors.newFixedThreadPool(3);   public  class DownLoadRunnable implements Runnable{        String murl;        private String FileName;        private long start;        private long end;       private Handler mhandler;    public DownLoadRunnable(String url,String filename,long start,long ent,Handler handler){            this.murl=url;            this.start=start;            this.end=ent;            this.FileName=filename;            this.mhandler=handler;        }        @Override        public void run() {            try {                URL http=new URL(murl);                HttpURLConnection conn= (HttpURLConnection) http.openConnection();                conn.setRequestMethod("GET");                conn.setReadTimeout(5000);                //通过Range字段设置请求的数据长度                conn.setRequestProperty("Range", "bytes=" + start + "-" + end);//设置请求的数据长度                //写入本地文件  rwd可读可写                RandomAccessFile access=new RandomAccessFile(new File(FileName),"rwd");                access.seek(start);//从start开始写                //写入数据                InputStream in=conn.getInputStream();                byte[]b=new byte[1024*4];                int len=0;                while((len=in.read(b))!=-1){//往access中读数据                    access.write(b,0,len);                }                /*关闭*/                if (access!=null){                    access.close();                }                if (in!=null){                    in.close();                }                //下载完成以后发送消息                Message message=Message.obtain();                message.what = 1;                mhandler.sendMessage(message);            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }    public void downFlie(String url){        try {            URL httpurl=new URL(url);            HttpURLConnection conn= (HttpURLConnection) httpurl.openConnection();            conn.setRequestMethod("GET");            conn.setReadTimeout(5000);            int count=conn.getContentLength();//获取数据长度            int block=count/3;//分三次下载            String name="zxy.jpg";            //下载的保存地址            File parent= Environment.getExternalStorageDirectory();//获取sd卡的父文件路径            File fileDownLoad=new File(parent,name);            /***分三次下载  最后一次把剩下的数据全部下载  16/3  第三次下载4个数据长度**/            for(int i=0;i<3;i++){                long _start=i*block;//从上一次停止的地方开始下载                long _ent=(i+1)*block-1;//下载的终点                if(i==2){//最后一次全部下载                    _ent=count;                }                DownLoadRunnable runnale=new DownLoadRunnable(url,fileDownLoad.getAbsolutePath(),_start,_ent,mhandler);                //通过线程池提交任务                threadPool.execute(runnale);            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}



 MainActivity.java类中代码如下:

public class MainActivity extends AppCompatActivity {    Button button;    TextView textView;    private int count=0;    private Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            int result=msg.what;            count+=result;            if(count==3){                textView.setText("下载完成!");            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button= (Button) findViewById(R.id.button);        textView=(TextView)findViewById(R.id.textView);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                new Thread(){                    @Override                    public void run() {                        DownLoad downLoad=new DownLoad(handler);                        //                        String urlo="http://localhost:8080/web3/zxy.jpg";                        downLoad.downFlie(urlo);                }                }.start();            }        });    }}

以上需要指出的是:由于在主线程不建议进行网络操作,所以新开一个子线程来下载图片,并在下载完成以后通过Handler来更新UI进行提示。

将localhost改成本地服务器的ip地址,如:http://192.168.1.101:8080/web3/zxy.jpg


main_layout.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.pss.downloadimagdome.MainActivity">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/button"/>    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="" /></RelativeLayout>


点击button后进入手机模拟器上的文件管理目录会有一张下载好的zxy.jpg图片。

运行结果:



0 0
原创粉丝点击