服务器之家

服务器之家 > 正文

Android实现下载文件功能的方法

时间:2021-03-05 15:50     来源/作者:Android开发网

本文所述为Android实现下载文件功能的完整示例代码,对于学习和研究android编程相信会有一定的帮助,尤其是对Android初学者有一定的借鉴价值。

完整功能代码如下:

?
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Main extends Activity {
 
 private TextView mTextView01;
 private EditText mEditText01;
 private Button mButton01;
 private static final String TAG = "DOWNLOADAPK";
 private String currentFilePath = "";
 private String currentTempFilePath = "";
 private String strURL="";
 private String fileEx="";
 private String fileNa="";
 
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  mTextView01 = (TextView)findViewById(R.id.myTextView1);
  mButton01 = (Button)findViewById(R.id.myButton1);
  mEditText01 =(EditText)findViewById(R.id.myEditText1);
 
  mButton01.setOnClickListener(new Button.OnClickListener()
  {
  public void onClick(View v)
  {
   // 文件会下载至local端
   mTextView01.setText("下载中...");
   strURL = mEditText01.getText().toString();
   /*取得欲安装程序之文件名称*/
   fileEx = strURL.substring(strURL.lastIndexOf(".")
   +1,strURL.length()).toLowerCase();
   fileNa = strURL.substring(strURL.lastIndexOf("/")
   +1,strURL.lastIndexOf("."));
   getFile(strURL);
   }
  }
  );
  
  mEditText01.setOnClickListener(new EditText.OnClickListener()
  {
 
  public void onClick(View arg0){
   mEditText01.setText("");
   mTextView01.setText("远程安装程序(请输入URL)");
  }
  });
 }
 
 /* 处理下载URL文件自定义函数 */
 private void getFile(final String strPath) {
  try
  {
  if (strPath.equals(currentFilePath) )
  {
   getDataSource(strPath);
  }
  currentFilePath = strPath;
  Runnable r = new Runnable()
  {
   public void run()
   {
   try
   {
    getDataSource(strPath);
   }
   catch (Exception e)
   {
    Log.e(TAG, e.getMessage(), e);
   }
   }
  };
  new Thread(r).start();
  }
  catch(Exception e)
  {
  e.printStackTrace();
  }
 }
 
  /*取得远程文件*/
 private void getDataSource(String strPath) throws Exception
 {
  if (!URLUtil.isNetworkUrl(strPath))
  {
  mTextView01.setText("错误的URL");
  }
  else
  {
  /*取得URL*/
  URL myURL = new URL(strPath);
  /*创建连接*/
  URLConnection conn = myURL.openConnection();
  conn.connect();
  /*InputStream 下载文件*/
  InputStream is = conn.getInputStream();
  if (is == null)
  {
   throw new RuntimeException("stream is null");
  }
  /*创建临时文件*/
  File myTempFile = File.createTempFile(fileNa, "."+fileEx);
  /*取得站存盘案路径*/
  currentTempFilePath = myTempFile.getAbsolutePath();
  /*将文件写入暂存盘*/
  FileOutputStream fos = new FileOutputStream(myTempFile);
  byte buf[] = new byte[128];
  do
  {
   int numread = is.read(buf);
   if (numread <= 0)
   {
   break;
   }
   fos.write(buf, 0, numread);
  }while (true);
  
  /*打开文件进行安装*/
  openFile(myTempFile);
  try
  {
   is.close();
  }
  catch (Exception ex)
  {
   Log.e(TAG, "error: " + ex.getMessage(), ex);
  }
  }
 }
  
 /* 在手机上打开文件的method */
 private void openFile(File f)
 {
  Intent intent = new Intent();
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.setAction(android.content.Intent.ACTION_VIEW);
  
  /* 调用getMIMEType()来取得MimeType */
  String type = getMIMEType(f);
  /* 设置intent的file与MimeType */
  intent.setDataAndType(Uri.fromFile(f),type);
  startActivity(intent);
 }
 
 /* 判断文件MimeType的method */
 private String getMIMEType(File f)
 {
  String type="";
  String fName=f.getName();
  /* 取得扩展名 */
  String end=fName.substring(fName.lastIndexOf(".")
  +1,fName.length()).toLowerCase();
  
  /* 依扩展名的类型决定MimeType */
  if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
  end.equals("xmf")||end.equals("ogg")||end.equals("wav"))
  {
  type = "audio";
  }
  else if(end.equals("3gp")||end.equals("mp4"))
  {
  type = "video";
  }
  else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
  end.equals("jpeg")||end.equals("bmp"))
  {
  type = "image";
  }
  else if(end.equals("apk"))
  {
  /* android.permission.INSTALL_PACKAGES */
  type = "application/vnd.android.package-archive";
  }
  else
  {
  type="*";
  }
  /*如果无法直接打开,就跳出软件列表给用户选择 */
  if(end.equals("apk"))
  {
  }
  else
  {
  type += "/*";
  }
  return type;
 }
 
 /*自定义删除文件方法*/
 private void delFile(String strFileName)
 {
  File myFile = new File(strFileName);
  if(myFile.exists())
  {
  myFile.delete();
  }
 }
 
 /*当Activity处于onPause状态时,更改TextView文字状态*/
 protected void onPause()
 {
  mTextView01 = (TextView)findViewById(R.id.myTextView1);
  mTextView01.setText("下载成功");
  super.onPause();
 }
 
 /*当Activity处于onResume状态时,删除临时文件*/
 protected void onResume()
 {
  /* 删除临时文件 */
  delFile(currentTempFilePath);
  super.onResume();
 }
}

读者可以在该实例的基础上进行修改与完善,使之更符合自身项目需求。

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部