HttpURLConnection 后台下载APK文件

1.下载方法
private File download() {
  HomeActivity app = HomeActivity.homeActivity();
  SpTryListenData spData = SpTryListenData.getInstance();
  String httpUrl="xxxxxxxxxxxxxxxxxxx"; 
// 后台地址
  Log.e("","cynos:downLoad state = 0");
  final String fileName = "MobileMusic503_014732W_feiyinghe.apk";
//下载文件的名字
  Log.e("","cynos:downLoad state = 1");
  int downLoad_num = 0;
  boolean downOK=false;
  final File file = new File(spData.downloadDir.getPath()+ "/" + fileName);
//下载文件的路径
  Log.e("","cynos:downLoad state = 2");
  try {
   URL url = new URL(httpUrl);
   Log.e("","cynos:downLoad state = "+httpUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(60000);//jdk 1.5换成这个,连接超时
          conn.setReadTimeout(60000);//jdk 1.5换成这个,读操作超时
    InputStream is = conn.getInputStream();
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buf = new byte[256];
    Log.i("Test", "cynos:downLoad wait");
    conn.connect();
    Log.i("Test", "cynos:downLoad connect OK !is downloading now");
    double count = 0;
    int downTime=0;
    int fileLength =  conn.getContentLength();
    Log.i("Test", "cynos:maxSize = "+fileLength);
    if (conn.getResponseCode() >= 400) {
    } else {
      boolean wifi=false;
     while (count <= 100) {
      if (is != null) {
       int numRead = is.read(buf);
       int loading = (downLoad_num/(fileLength/100));
       Log.e("", "cynos:downLoad_num = " + downLoad_num+"/"+fileLength+"   进度:"+loading);
       Message message=handler.obtainMessage();
       message.what=100;
       message.obj=loading;
       handler.sendMessage(message);
       downLoad_num += numRead; 
       downTime++;
       if (numRead <= 0) {  
        break;
       } else {
        fos.write(buf, 0, numRead);
       }
      } else {
       break;
      }
     }
    }
    
    Log.i("Test", "over:downLoad_num " + downLoad_num);
    Log.i("Test", "over:fileLength " + fileLength);
    if (downLoad_num+100 >= fileLength)
    {
     mProgress.dismiss();
     app.notifyShowToast("已下载咪咕音乐客户端 "+"\n"+file.getPath());
     Log.e("", "cynos:downLoad_num = "+file.getPath());
     Intent intent = new Intent();
     //执行动作
     intent.setAction(Intent.ACTION_VIEW);
     //执行的数据类型
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     intent.setDataAndType(Uri.parse("file://" +file.getPath()), "application/vnd.android.package-archive");
     startActivity(intent);
     
    }
    
    conn.disconnect();
    fos.close();
    is.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   app.hideProgressBar();
   app.notifyShowToast("下载失败,请检查网络连接或重新下载");
  }
  return file;
 }
2. 下载提示框。ProgressDialog初始
hprivate void downloadApk() {
  AlertDialog.Builder builder = new Builder(TryListenListActivity.this);
  builder.setTitle("下载咪咕音乐客户端");
  builder.setMessage("下载咪咕音乐客户端,获得海量精品音乐是否下载?");
  builder.setPositiveButton("确定下载", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    dialog.dismiss();
//    HomeActivity app = HomeActivity.homeActivity();
//    app.showProgressBar("请稍候,正在下载"+"0%");
    if (mProgress == null) {
     mProgress = new ProgressDialog(TryListenListActivity.this);
     mProgress.setMessage("正在下载,请稍后"+"0%");
     mProgress.setIndeterminate(false);
     mProgress.setCancelable(false);
     mProgress.show();
    }
    
    new Thread(new Runnable() {
     @Override
     public void run() {
      // TODO Auto-generated method stub
      download();
     }
    }).start();
   }
  });
  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    dialog.dismiss();
   }
  });
  builder.create();
  builder.show();
 }
 private ProgressDialog mProgress = null;
3.  发送小心不断更新 ProgressDialog
Handler handler=new Handler(){
  public void handleMessage(android.os.Message msg) {
   if(msg.what==100){
    final int a=(Integer) msg.obj;
    Log.e("", "cynos:downLoad_num = "+ a);
    HomeActivity app = HomeActivity.homeActivity();
    final String b=String.valueOf(a);
    new Handler().post(new Runnable() {
     @Override
     public void run() {
      // TODO Auto-generated method stub
      mProgress.setMessage("正在下载,请稍后"+b+"%");
     
     }
    });
    
    
    
   }
  };
 };
4. 弊端: 这不是servers 下载更新的 会一直显示在前台,等待下载完毕,下载过程中不能做其他的事情,建议使用notification
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值