MainActivity.javapackage com.example.mydownpre;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.RandomAccessFile;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;//MainActivity extends AppCompatActivitypublic class MainActivity extends AppCompatActivity {    /** Called when the activity is first created. */    private static final String Path="http://192.168.43.8/song/Csaprs-NarkomanPavlik.mp3";    private ProgressBar progressBar;    private TextView textView;    private Button button;    private int FileLength;    private int DownedFileLength=0;    private InputStream inputStream;    private URLConnection connection;    private OutputStream outputStream;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        progressBar=(ProgressBar) findViewById(R.id.progress);        textView=(TextView) findViewById(R.id.text);        button=(Button) findViewById(R.id.button);        button.setOnClickListener(new ButtonListener());    }    class ButtonListener implements OnClickListener{        @Override        public void onClick(View v) {            DownedFileLength=0;            // TODO Auto-generated method stub            Thread thread=new Thread(){                public void run(){                    try {                        DownFile(Path);                    } catch (Exception e) {                        // TODO: handle exception                    }                }            };            thread.start();        }    }    private Handler handler=new Handler()    {        public void handleMessage(Message msg)        {            if (!Thread.currentThread().isInterrupted()) {                switch (msg.what) {                    case 0:                        progressBar.setMax(FileLength);                        Log.i("文件长度----------->", progressBar.getMax()+"");                        break;                    case 1:                        progressBar.setProgress(DownedFileLength);                        int x=DownedFileLength*100/FileLength;                        textView.setText(x+"%");                        break;                    case 2:                        Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();                        break;                    default:                        break;                }            }        }    };    private void DownFile(String urlString)    {        /*         * 连接到服务器         */        try {            URL url=new URL(urlString);            connection=url.openConnection();            if (connection.getReadTimeout()==5) {                Log.i("---------->", "当前网络有问题");                // return;            }            inputStream=connection.getInputStream();        } catch (MalformedURLException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        /*         * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建         */        String savePAth=Environment.getExternalStorageDirectory()+"/DownFile";        File file1=new File(savePAth);        if (!file1.exists()) {            file1.mkdir();        }        String savePathString=Environment.getExternalStorageDirectory()+"/DownFile/"+"DJ.mp3";        File file =new File(savePathString);        if (!file.exists()) {            try {                file.createNewFile();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        /*         * 向SD卡中写入文件,用Handle传递线程         */        Message message=new Message();        try {            outputStream=new FileOutputStream(file);            byte [] buffer=new byte[1024*4];            FileLength=connection.getContentLength();            message.what=0;            handler.sendMessage(message);            while (DownedFileLength<FileLength) {                outputStream.write(buffer);                DownedFileLength+=inputStream.read(buffer);                Log.i("-------->", DownedFileLength+"");                Message message1=new Message();                message1.what=1;                handler.sendMessage(message1);            }            Message message2=new Message();            message2.what=2;            handler.sendMessage(message2);        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}第二步  activity-main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">    <ProgressBar        android:id="@+id/progress"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1" />    <TextView        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="20dp"        android:layout_weight="1"        android:text="TextView" />    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="15dp"        android:layout_weight="1"        android:text="Button" /></LinearLayout>第三步:权限   <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />        android:usesCleartextTraffic="true"

更多相关文章

  1. Pycharm安装PyQt5的详细教程
  2. NPM 和webpack 的基础使用
  3. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  4. 文件对应
  5. Android(安卓)的网络编程(8)-文件上传功能
  6. Android(安卓)图片的缓存机制分析
  7. Android(安卓)IjkPlayer 视频播放器
  8. Android实时抓取日志,生成文件
  9. android保存第一次安装状态并初始化数据

随机推荐

  1. MS目录
  2. android闹钟――原代码
  3. Android(安卓)之 ServiceManager与服务管
  4. Android获取前台进程包名
  5. 从NDK在非Root手机上的调试原理探讨Andro
  6. 第二篇 ( wcf 与 android 图片上传下载)
  7. AndroidStudio中gradle异常:unexpected en
  8. Android(安卓)中文 API (22) ―― MultiAut
  9. 搭建Android(安卓)NDK开发环境
  10. Android(安卓)电子罗盘--指南针(方向传感