文件下载

来源:互联网 发布:安能快递有淘宝店用吗 编辑:程序博客网 时间:2024/06/06 03:53

我们实现的效果是点击button按钮实现文件的开始下载 所以我们布局中的代码 也就显而易见了 让我们来一起看一下布局中的实现代码啊!

<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"    tools:context="com.example.download.MainActivity" >    <Button        android:id="@+id/download"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:onClick="download"        android:text="下载文件" /></RelativeLayout>

//实现文件的下载 我们要给按钮实现监听 让我们一起看一下主类中的实现代码

import java.io.File;import android.support.v7.app.ActionBarActivity;import android.app.AlertDialog.Builder;import android.content.DialogInterface;import android.content.Intent;import android.content.DialogInterface.OnClickListener;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.view.LayoutInflater;import android.view.View;import android.widget.LinearLayout;import android.widget.ProgressBar;public class MainActivity extends ActionBarActivity {    private ProgressBar progressbar1;//进度条     //进度条进度    private int pregress_cont;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    //点击按钮实现文件下载    public void download(View v){//      开始下载文件        new Thread(){//耗时操作在子线程中操作            public void run() {                Download.loadFile("http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk",mHandler);            };        }.start();//      弹出是否进入后台下载框        LinearLayout layout = (LinearLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.loading,null);        progressbar1 = (ProgressBar) layout.findViewById(R.id.progressBar1);        Builder my_builder  = new Builder(MainActivity.this);        my_builder.setView(layout);        my_builder.setPositiveButton("后台下载", new OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {            }        });        my_builder.show();    }    private Handler mHandler = new Handler(){        public void handleMessage(Message msg){            switch (msg.what){            case 11:                  // 正在下载   设置进度条位置                   pregress_cont = msg.arg1;//获得传递过来的进度                progressbar1.setProgress(pregress_cont);//将进度值设置给进度条                break;              case 200:  //              通知安装下载的apk                Intent intent = new Intent(Intent.ACTION_VIEW);                intent.setDataAndType(Uri.fromFile(new File(Environment                        .getExternalStorageDirectory(), "baiduxinwen.apk")),                        "application/vnd.android.package-archive");                MainActivity.this.startActivity(intent);                break;             }          };      };}

//在主方法中我们还需要一个封装的链接网络请求数据的类 让我们来见证一下吧

import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.os.Environment;import android.os.Handler;import android.os.Message;public class Download {    //下载文件    public static void loadFile(String url,Handler mHandler) {        HttpClient client = new DefaultHttpClient();        HttpGet get = new HttpGet(url);        HttpResponse response;        try {            response = client.execute(get);            HttpEntity entity = response.getEntity();            float length = entity.getContentLength();            InputStream is = entity.getContent();//返回一个流文件            FileOutputStream fileOutputStream = null;            if (is != null) {//如果文件不等于空   读取文件                File file = new File(Environment.getExternalStorageDirectory(),                        "baiduxinwen.apk");                fileOutputStream = new FileOutputStream(file);                byte[] buf = new byte[1024];                int ch = -1;                float count = 0;                while ((ch = is.read(buf)) != -1) {                    fileOutputStream.write(buf, 0, ch);                    count += ch;//                  sendMsg(1,(int) (count*100/length));                    //正在下载,计算下载大小                    int pregress_cont = (int) (((float) count / length) * 100);                     Message mes = new Message();                    mes.arg1 = pregress_cont;                    mes.what= 11;                    mHandler.sendMessage(mes);                }            }            //下载完成,发送消息---通知安装            mHandler.sendEmptyMessage(200);            fileOutputStream.flush();            if (fileOutputStream != null) {                fileOutputStream.close();            }        } catch (Exception e) {//          sendMsg(-1,0);        }    }}

不要忘了添加连接网络的权限哦!不然是不能下载的

就是上面的额这个代码 我们就能实现从网络上面下载文件并安装了 让我们看一下辛苦半天之后的效果图吧

//点击button按钮就能出现下面的效果图 显示下载的进度
这里写图片描述

下载完成后就会进度下载的界面让你选择是取消安装还是安装
这里写图片描述

1 0
原创粉丝点击