版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
【移動(dòng)應(yīng)用開(kāi)發(fā)技術(shù)】Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能
Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。1.泛型AysncTask<Params,Progress,Result>Params:?jiǎn)?dòng)任務(wù)時(shí)傳入的參數(shù),通過(guò)調(diào)用asyncTask.execute(param)方法傳入。Progress:后臺(tái)任務(wù)執(zhí)行的進(jìn)度,若不用顯示進(jìn)度條,則不需要指定。Result:后臺(tái)任務(wù)結(jié)束時(shí)返回的結(jié)果。2.重要方法doInBackground(Params...params):必須重寫(xiě)的方法,后臺(tái)任務(wù)就在這里執(zhí)行,會(huì)開(kāi)啟一個(gè)新的線(xiàn)程。params為啟動(dòng)任務(wù)時(shí)傳入的參數(shù),參數(shù)個(gè)數(shù)不定。onPreExecute():在主線(xiàn)程中調(diào)用,在后臺(tái)任務(wù)開(kāi)啟前的操作在這里進(jìn)行,例如顯示一個(gè)進(jìn)度條對(duì)話(huà)框。onPostExecute(Resultresult):當(dāng)后臺(tái)任務(wù)結(jié)束后,在主線(xiàn)程中調(diào)用,處理doInBackground()方法返回的結(jié)果。onProgressUpdate(Progress...values):當(dāng)在doInBackground()中調(diào)用publishProgress(Progress...values)時(shí),返回主線(xiàn)程中調(diào)用,這里的參數(shù)個(gè)數(shù)也是不定的。onCancelled():取消任務(wù)。3.注意事項(xiàng)(1)execute()方法必須在主線(xiàn)程中調(diào)用;(2)AsyncTask實(shí)例必須在主線(xiàn)程中創(chuàng)建;(3)不要手動(dòng)調(diào)用doInBackground()、onPreExecute()、onPostExecute()、onProgressUpdate()方法;(4)注意防止內(nèi)存泄漏,在doInBackground()方法中若出現(xiàn)對(duì)Activity的強(qiáng)引用,可能會(huì)造成內(nèi)存泄漏。4.下載文件動(dòng)態(tài)更新進(jìn)度條(未封裝)布局:<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="/apk/res/android"
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context="com.studying.asynctaskdemo.MainActivity">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0"
/>
<Button
android:id="@+id/download"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="20dp"
android:text="@string/start_btn"
/>
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/waiting"
/>
</LinearLayout>Activity:public
class
MainActivity
extends
Activity
{
private
static
final
String
FILE_NAME
=
"test.pdf";//下載文件的名稱(chēng)
private
static
final
String
PDF_URL
=
"/class/assist/118/1328281/AsyncTask.pdf";
private
ProgressBar
mProgressBar;
private
Button
mDownloadBtn;
private
TextView
mStatus;
@Override
protected
void
onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private
void
initView()
{
mProgressBar
=
(ProgressBar)
findViewById(R.gressBar);
mDownloadBtn
=
(Button)
findViewById(R.id.download);
mStatus
=
(TextView)
findViewById(R.id.status);
}
private
void
setListener()
{
mDownloadBtn.setOnClickListener(new
View.OnClickListener()
{
@Override
public
void
onClick(View
v)
{
//AsyncTask實(shí)例必須在主線(xiàn)程創(chuàng)建
DownloadAsyncTask
asyncTask
=
new
DownloadAsyncTask();
asyncTask.execute(PDF_URL);
}
});
}
/**
*
泛型:
*
String:傳入?yún)?shù)為文件下載地址
*
Integer:下載過(guò)程中更新ProgressBar的進(jìn)度
*
Boolean:是否下載成功
*/
private
class
DownloadAsyncTask
extends
AsyncTask<String,
Integer,
Boolean>
{
private
String
mFilePath;//下載文件的保存路徑
@Override
protected
Boolean
doInBackground(String...
params)
{
if
(params
!=
null
&&
params.length
>
0)
{
String
pdfUrl
=
params[0];
try
{
URL
url
=
new
URL(pdfUrl);
URLConnection
urlConnection
=
url.openConnection();
InputStream
in
=
urlConnection.getInputStream();
int
contentLength
=
urlConnection.getContentLength();//獲取內(nèi)容總長(zhǎng)度
mFilePath
=
Environment.getExternalStorageDirectory()
+
File.separator
+
FILE_NAME;
//若存在同名文件則刪除
File
pdfFile
=
new
File(mFilePath);
if
(pdfFile.exists())
{
boolean
result
=
pdfFile.delete();
if
(!result)
{
return
false;
}
}
int
downloadSize
=
0;//已經(jīng)下載的大小
byte[]
bytes
=
new
byte[1024];
int
length
=
0;
OutputStream
out
=
new
FileOutputStream(mFilePath);
while
((length
=
in.read(bytes))
!=
-1)
{
out.write(bytes,
0,
length);
downloadSize
+=
length;
publishProgress(downloadSize
/
contentLength
*
100);
}
in.close();
out.close();
}
catch
(IOException
e)
{
e.printStackTrace();
return
false;
}
}
else
{
return
false;
}
return
true;
}
@Override
protected
void
onPreExecute()
{
super.onPreExecute();
mDownloadBtn.setText("下載中");
mDownloadBtn.setEnabled(false);
mStatus.setText("下載中");
mProgressBar.setProgress(0);
}
@Override
protected
void
onPostExecute(Boolean
aBoolean)
{
super.onPostExecute(aBoolean);
mDownloadBtn.setText("下載完成");
mStatus.setText(aBoolean
?
"下載完成"
+
mFilePath
:
"下載失敗");
}
@Override
protected
void
onProgressUpdate(Integer...
values)
{
super.onProgressUpdate(values);
if
(values
!=
null
&&
values.length
>
0)
{
mProgressBar.setProgress(values[0]);
}
}
}
}5.下載文件動(dòng)態(tài)更新進(jìn)度條(封裝)Activity:public
class
MainActivity
extends
Activity
{
private
static
final
String
FILE_NAME
=
"test.pdf";
private
static
final
String
PDF_URL
=
"/class/assist/118/1328281/AsyncTask.pdf";
private
ProgressBar
mProgressBar;
private
Button
mDownloadBtn;
private
TextView
mStatus;
@Override
protected
void
onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private
void
initView()
{
mProgressBar
=
(ProgressBar)
findViewById(R.gressBar);
mDownloadBtn
=
(Button)
findViewById(R.id.download);
mStatus
=
(TextView)
findViewById(R.id.status);
}
private
void
setListener()
{
mDownloadBtn.setOnClickListener(new
View.OnClickListener()
{
@Override
public
void
onClick(View
v)
{
String
localPath
=
Environment.getExternalStorageDirectory()
+
File.separator
+
FILE_NAME;
DownloadHelper.download(PDF_URL,
localPath,
new
DownloadHelper.OnDownloadListener()
{
@Override
public
void
onStart()
{
mDownloadBtn.setText("下載中");
mDownloadBtn.setEnabled(false);
mStatus.setText("下載中");
mProgressBar.setProgress(0);
}
@Override
public
void
onSuccess(File
file)
{
mDownloadBtn.setText("下載完成");
mStatus.setText(String.format("下載完成:%s",
file.getPath()));
}
@Override
public
void
onFail(File
file,
String
failInfo)
{
mDownloadBtn.setText("開(kāi)始下載");
mDownloadBtn.setEnabled(true);
mStatus.setText(String.format("下載失?。?s",
failInfo));
}
@Override
public
void
onProgress(int
progress)
{
mProgressBar.setProgress(progress);
}
});
}
});
}
}DownloadHelper:class
DownloadHelper
{
static
void
download(String
url,
String
localPath,
OnDownloadListener
listener)
{
DownloadAsyncTask
task
=
new
DownloadAsyncTask(url,
localPath,
listener);
task.execute();
}
private
static
class
DownloadAsyncTask
extends
AsyncTask<String,
Integer,
Boolean>
{
private
String
mFailInfo;
private
String
mUrl;
private
String
mFilePath;
private
OnDownloadListener
mListener;
DownloadAsyncTask(String
mUrl,
String
mFilePath,
OnDownloadListener
mListener)
{
this.mUrl
=
mUrl;
this.mFilePath
=
mFilePath;
this.mListener
=
mListener;
}
@Override
protected
Boolean
doInBackground(String...
params)
{
String
pdfUrl
=
mUrl;
try
{
URL
url
=
new
URL(pdfUrl);
URLConnection
urlConnection
=
url.openConnection();
InputStream
in
=
urlConnection.getInputStream();
int
contentLength
=
urlConnection.getContentLength();
File
pdfFile
=
new
File(mFilePath);
if
(pdfFile.exists())
{
boolean
result
=
pdfFile.delete();
if
(!result)
{
mFailInfo
=
"存儲(chǔ)路徑下的同名文件刪除失敗!";
return
false;
}
}
int
downloadSize
=
0;
byte[]
bytes
=
new
byte[1024];
int
length;
OutputStream
out
=
new
FileOutputStream(mFilePath);
while
((length
=
in.read(bytes))
!=
-1)
{
out.write(bytes,
0,
length);
downloadSize
+=
length;
publishProgress(downloadSize
/
contentLength
*
100);
}
in.close();
out.close();
}
catch
(IOException
e)
{
e.printStackTrace();
mFailInfo
=
e.getMessage();
r
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 養(yǎng)老院家屬探訪(fǎng)制度
- 企業(yè)內(nèi)部控制與合規(guī)制度
- 公共交通服務(wù)設(shè)施維護(hù)制度
- 2026年藝術(shù)鑒賞理論經(jīng)典畫(huà)作解析測(cè)驗(yàn)題
- 2026年數(shù)據(jù)安全技術(shù)與方法安全管理員專(zhuān)業(yè)知識(shí)測(cè)試題
- 2026年城市智能交通系統(tǒng)建設(shè)方案模擬題
- 2026年建筑工程設(shè)計(jì)高級(jí)工程師評(píng)審資料及題庫(kù)詳解
- 2026年醫(yī)學(xué)基礎(chǔ)人體解剖學(xué)知識(shí)點(diǎn)測(cè)試
- 2026年甲醛治理效果保證合同
- 2026年急救技能培訓(xùn)合同
- 北京市順義區(qū)2025-2026學(xué)年八年級(jí)上學(xué)期期末考試英語(yǔ)試題(原卷版+解析版)
- 中學(xué)生冬季防溺水主題安全教育宣傳活動(dòng)
- 2026年藥廠安全生產(chǎn)知識(shí)培訓(xùn)試題(達(dá)標(biāo)題)
- 初中九年級(jí)上一元二次方程計(jì)算練習(xí)題及答案詳解B2
- 冷庫(kù)防護(hù)制度規(guī)范
- 2026年生產(chǎn)管理崗入職性格測(cè)試題及答案
- 廣東省廣州市番禺區(qū)2026屆高一數(shù)學(xué)第一學(xué)期期末聯(lián)考試題含解析
- 2026年廣東省佛山市高三語(yǔ)文聯(lián)合診斷性考試作文題及3篇范文:可以“重讀”甚至“重構(gòu)”這些過(guò)往
- 2025年汽車(chē)駕駛員技師考試試題及答案含答案
- 觀看煤礦警示教育片寫(xiě)心得體會(huì)
- 2025年國(guó)際中文教師證書(shū)考試真題附答案
評(píng)論
0/150
提交評(píng)論