Android實現(xiàn)下載文件功能的方法
本文所述為Android實現(xiàn)下載文件功能的完整示例代碼,對于學(xué)習(xí)和研究android編程相信會有一定的幫助,尤其是對Android初學(xué)者有一定的借鑒價值。
完整功能代碼如下:
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文件自定義函數(shù) */
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);
/*創(chuàng)建連接*/
URLConnection conn = myURL.openConnection();
conn.connect();
/*InputStream 下載文件*/
InputStream is = conn.getInputStream();
if (is == null)
{
throw new RuntimeException("stream is null");
}
/*創(chuàng)建臨時文件*/
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);
/* 調(diào)用getMIMEType()來取得MimeType */
String type = getMIMEType(f);
/* 設(shè)置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();
}
}
/*當(dāng)Activity處于onPause狀態(tài)時,更改TextView文字狀態(tài)*/
protected void onPause()
{
mTextView01 = (TextView)findViewById(R.id.myTextView1);
mTextView01.setText("下載成功");
super.onPause();
}
/*當(dāng)Activity處于onResume狀態(tài)時,刪除臨時文件*/
protected void onResume()
{
/* 刪除臨時文件 */
delFile(currentTempFilePath);
super.onResume();
}
}
讀者可以在該實例的基礎(chǔ)上進行修改與完善,使之更符合自身項目需求。
- Android 下載文件通知欄顯示進度條功能的實例代碼
- Android中使用AsyncTask實現(xiàn)下載文件動態(tài)更新進度條功能
- android中實現(xiàn)OkHttp下載文件并帶進度條
- android實現(xiàn)多線程下載文件(支持暫停、取消、斷點續(xù)傳)
- Android實現(xiàn)Service下載文件,Notification顯示下載進度的示例
- 使用Android系統(tǒng)提供的DownloadManager來下載文件
- Android通過SOCKET下載文件的方法
- Android實現(xiàn)多線程下載文件的方法
- Android使用Handler實現(xiàn)下載文件功能
相關(guān)文章
Android使用Intent實現(xiàn)頁面跳轉(zhuǎn)
這篇文章主要為大家詳細介紹了Android使用Intent實現(xiàn)頁面跳轉(zhuǎn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
Android 圖片縮放與旋轉(zhuǎn)的實現(xiàn)詳解
本篇文章是對在Android中實現(xiàn)圖片縮放與旋轉(zhuǎn)的方法進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Android EditText隨輸入法一起移動并懸浮在輸入法之上的示例代碼
這篇文章主要介紹了Android EditText隨輸入法一起移動并懸浮在輸入法之上,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
Android點擊Button實現(xiàn)切換點擊圖片效果的示例
今天小編就為大家分享一篇關(guān)于Android點擊Button實現(xiàn)切換點擊圖片效果的示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
Android自定義ViewGroup(側(cè)滑菜單)詳解及簡單實例
這篇文章主要介紹了Android自定義ViewGroup(側(cè)滑菜單)詳解及簡單實例的相關(guān)資料,需要的朋友可以參考下2017-02-02
詳解用RxJava實現(xiàn)事件總線(Event Bus)
本篇文章主要介紹了用RxJava實現(xiàn)事件總線(Event Bus),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11

