服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android使用Handler实现下载文件功能

Android使用Handler实现下载文件功能

2022-03-01 15:38轻扰时光 Android

这篇文章主要为大家详细介绍了Android使用Handler实现下载文件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android实现下载文件的具体代码,供大家参考,具体内容如下

1.实现效果

直接上图:

Android使用Handler实现下载文件功能

2.代码实现

在AndroidManifest.xml文件中声明申请的权限,如下所示:

?
1
2
3
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

新建一个名为DownloadDemo的项目,activity_main.xml代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center_horizontal"
 android:orientation="vertical"
 tools:context=".MainActivity">
 
 <Button
  android:id="@+id/button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="下载" />
 
 <ProgressBar
  android:id="@+id/progressBar"
  style="?android:attr/progressBarStyleHorizontal"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="10dp"
  android:max="100"
  android:progress="0" />
</LinearLayout>

MainActivity.class代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
 public static final String APP_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
 public static final int DOWNLOAD_MESSAGE_CODE = 100001;
 private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
 public static final int REQUEST_CODE = 1;
 private Button button;
 private ProgressBar progressBar;
 private MyHandler mHandler;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initView();
  askPermission();
  mHandler = new MyHandler(this);
 }
 
 public static class MyHandler extends Handler {
  final WeakReference<MainActivity> mWeakReference;
 
  public MyHandler(MainActivity activity) {
   this.mWeakReference = new WeakReference<>(activity);
  }
 
  @Override
  public void handleMessage(Message msg) {
   MainActivity activity = mWeakReference.get();
   super.handleMessage(msg);
   switch (msg.what) {
    case DOWNLOAD_MESSAGE_CODE:
     activity.progressBar.setProgress((Integer) msg.obj);
     if (((Integer) msg.obj) == 100) {
      Toast.makeText(activity, "文件下载已完成!", Toast.LENGTH_SHORT).show();
     }
     break;
    case DOWNLOAD_MESSAGE_FAIL_CODE:
     Toast.makeText(activity, "文件下载失败!", Toast.LENGTH_SHORT).show();
     break;
   }
  }
 }
 
 /**
  * 申请权限
  */
 private void askPermission() {
  //将所需申请的权限添加到List集合中
  List<String> permissionList = new ArrayList<>();
  if (ContextCompat.checkSelfPermission(MainActivity.this,
    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
   permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
  }
  //判断权限列表是否为空,若不为空,则向用户申请权限,否则则直接执行操作
  if (!permissionList.isEmpty()) {
   String[] permissions = permissionList.toArray(new String[permissionList.size()]);
   ActivityCompat.requestPermissions(MainActivity.this, permissions, REQUEST_CODE);
  } else {
   //TODO
   button.setOnClickListener(this);
  }
 }
 
 /**
  * 用户对请求权限的dialog做出响应之后,会处理请求权限的响应
  *
  * @param requestCode 请求码
  * @param permissions 权限的集合
  * @param grantResults 权限授予的结果
  */
 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  switch (requestCode) {
   case REQUEST_CODE:
    if (grantResults.length > 0) {
     for (int result : grantResults) {
      if (result != PackageManager.PERMISSION_GRANTED) {
       Toast.makeText(this, "必须同意所有权限才能使用本程序", Toast.LENGTH_SHORT).show();
       finish();
       return;
      }
     }
     //TODO
     button.setOnClickListener(this);
    } else {
     Toast.makeText(this, "权限申请失败!", Toast.LENGTH_SHORT).show();
     finish();
    }
    break;
   default:
    break;
  }
 }
 
 /**
  * 点击事件
  *
  * @param v
  */
 @Override
 public void onClick(View v) {
  switch (v.getId()) {
   case R.id.button:
    new Thread(new Runnable() {
     @Override
     public void run() {
      download(APP_URL);
     }
    }).start();
    break;
  }
 }
 
 /**
  * 下载
  *
  * @param appUrl
  */
 private void download(String appUrl) {
  try {
   //实例化一个url对象
   URL url = new URL(appUrl);
   //获取URLConnection对象
   URLConnection urlConnection = url.openConnection();
   //获取输入流
   InputStream inputStream = urlConnection.getInputStream();
   //获取文件的总长度
   int contentLength = urlConnection.getContentLength();
   //设置软件下载到手机存储的位置文件夹名称
   String downloadFolderName = Environment.getExternalStorageDirectory()
     + File.separator + "MyApp" + File.separator;
   File file = new File(downloadFolderName);
   //若文件夹不存在则进行创建
   if (!file.exists()) {
    file.mkdir();
   }
   String fileName = downloadFolderName + "chaixingsi.apk";
   File apkFile = new File(fileName);
   if (apkFile.exists()) {
    apkFile.delete();
   }
   int downloadContentLength = 0;
   int length = 0;
   byte[] bytes = new byte[1024];
   OutputStream outputStream = new FileOutputStream(fileName);
   while ((length = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, length);
    downloadContentLength += length;
    /**
     * 发送消息通知主线程去更新UI
     */
    Message message = Message.obtain();
    message.obj = downloadContentLength * 100 / contentLength;
    message.what = DOWNLOAD_MESSAGE_CODE;
    mHandler.sendMessage(message);
   }
   inputStream.close();
   outputStream.close();
  } catch (MalformedURLException e) {
   //下载失败的话也发送消息
   notifyDownloadFailed();
   e.printStackTrace();
  } catch (IOException e) {
   notifyDownloadFailed();
   e.printStackTrace();
  }
 }
 
 /**
  * 通知下载失败
  */
 private void notifyDownloadFailed() {
  Message message = Message.obtain();
  message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
  mHandler.sendMessage(message);
 }
 
 /**
  * 初始化视图
  */
 private void initView() {
  button = findViewById(R.id.button);
  progressBar = findViewById(R.id.progressBar);
 }
}

3.快捷键总结

提取方法:Ctrl+Alt+M;
提取变量:Ctrl+Alt+V;
提取常量:Ctrl+Alt+C;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qingjianduoyun/article/details/80628571

延伸 · 阅读

精彩推荐