这几天更新的文章都是与安卓程序更新有关的,昨天讲了使用ProgressDialog来呈现安卓程序更新时的UI交互,今天来实现下载的具体过程。
先说说本文实现的效果,将网络文件,例如:http://117.177.249.153/rpcs.myapp.com/myapp/rcps/d/1000017149/com.tencent.mtt_1000017149_170221201645a.apk这是腾讯的QQ浏览器文件,官方的。下载至本地文件夹daimadogdown中,并以下载地址中的com.tencent.mtt_1000017149_170221201645a.apk为文件名。再加上昨天的ProgressDialog对话框进行UI交互,子线程与主线程(UI线程)交互使用handler。
实现代码如下:
public class MainActivity extends AppCompatActivity {private Button bt1; private Button qr; Dialog dailog; ProgressDialog pd; Handler handler; String path="http://117.177.249.153/rpcs.myapp.com/myapp/rcps/d/1000017149/com.tencent.mtt_1000017149_170221201645a.apk"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt1= (Button) findViewById(R.id.button); handler=new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what==1){pd.setProgress(msg.arg1); }else if (msg.what==0){ pd.dismiss(); } } }; bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {showpress(); new Thread(){ @Override public void run() { HttpURLConnection connt=null; FileOutputStream fos=null; InputStream in=null; File file=null; try { URL url = new URL(path); connt = (HttpURLConnection) url.openConnection(); connt .setRequestProperty("Accept-Encoding", "identity"); connt.setRequestMethod("GET"); int wenjiancd=connt.getContentLength(); int code = connt.getResponseCode(); if (code == 200) { file = new File(Environment.getExternalStorageDirectory(), "/daimadogdown/"+getfilename()); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } fos = new FileOutputStream(file); in = connt.getInputStream(); int len = -1; int jdcd=0; System.out.println(wenjiancd); byte[] b = new byte[1024]; while ((len = in.read(b)) != -1) { jdcd+=len; Message msg=Message.obtain(); System.out.println((int)((float)jdcd/wenjiancd*100)); msg.arg1=(int)((float)jdcd/wenjiancd*100); msg.what=1; handler.sendMessage(msg); fos.write(b, 0, len); } fos.flush(); handler.sendEmptyMessage(0); } }catch (IOException e){ e.printStackTrace(); }finally { try{ if (fos!=null)fos.close(); if (in!=null)in.close(); if (connt!=null)connt.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); } }); } //获取文件名private String getfilename(){int sata=path.lastIndexOf("/"); return path.substring(sata+1);} //进度对话框 private void showpress(){ pd=new ProgressDialog(MainActivity.this); pd.setTitle("下载更新"); pd.setMessage("下载中,请稍后...."); pd.setCancelable(false); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMax(100); pd.show(); }}
效果如下图所示:
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/241645.html