編輯:關於Android編程
好久好久沒寫博客了,這一個多月的時間,自己的身體和心理狀態對我來說都是差勁的。不是不想寫博客,而是實在寫不出有觀點的新穎的東西,面臨將要工作這一現實,內心還是有一丟丟擔心和憂慮的。
為了保持良好的博客習慣,我還是把這篇筆記貼了出來,雖然他是翻譯的google的api,但是,希望這篇文章可以幫到和我一樣英語不好的人,讓我們一同進步。
AsyncTask enables proper(恰當的) and easy use of the UI thread. This class allows to perform background operations and publish(發布) results on the UI thread without having to manipulate threads and/or handlers.
一種異步處理機制,他不需要操作線程或者使用handler就可以控制UI線程
AsyncTask is designed to be a helper class aroundThread
andHandler
and does not constitute(構成) a generic threading framework. AsyncTasks should ideally be used for(可用於) short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by thejava.util.concurrent
package such asExecutor
,ThreadPoolExecutor
andFutureTask
.
這一段大概說,這個類只是個為了方便使用thread和handler的輔助類,不能構成一個框架,他只能進行斷的線程操作。要想進行長的線程操作,還要去java.util.concurrent中找Executor
,ThreadPoolExecutor
andFutureTask(話說這三個是什麼鬼)
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types(泛型), calledParams
,Progress
andResult
, and 4 steps, calledonPreExecute
,doInBackground
,onProgressUpdate
andonPostExecute
.
講了什麼是異步任務,好吧是在翻譯不通順,只能自己寫一下了:就是在非UI線程上進行運算,在然後將結果更新在UI線程上
一個AsynTask的定義通過三種泛型calledParams
,Progress
andResult
和onPreExecute
,doInBackground
,onProgressUpdate
andonPostExecute
四個步驟
For more information about using tasks and threads, read theProcesses and Threadsdeveloper guide.
有關更多的使用線程的信息,請讀。。。開發者指南
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)
), and most often will override a second one (onPostExecute(Result)
.)
該類是抽象類,使用必須子類繼承,並至少覆蓋一個方法doInBackground(Params...)而且通常重寫onPostExecute(Result)方法
栗子:
private class DownloadFilesTask extends AsyncTask { //注意繼承asynctask要寫泛型
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called 如果cancel被調用 異步任務將會提早退出
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
這裡是啟動任務的方法:
new DownloadFilesTask().execute(url1, url2, url3);
The three types used by an asynchronous task are the following:
Params
, the type of the parameters sent to the task upon execution. 執行任務時所需要的參數的泛型Progress
, the type of the progress units published during the background computation. 執行任務時,後台運行的進度的泛型Result
, the type of the result of the background computation. 後台運算的結果的泛型
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the typeVoid
:
這三個泛型不一定都用的上,不用的用void就可以了
When an asynchronous task is executed, the task goes through 4 steps: 執行一個異步任務 要四部
onPreExecute()
, invoked(參與,引用) on the UI thread before the task is executed. This step is normally used to setup the task, for instance(例如) by showing a progress bar in the user interface.
在執行異步任務前,調用該方法,注意:該方法運行在UI線程上。這一步通常用於設置任務,比如通過用戶界面顯示一個進度條
doInBackground(Params...)
, invoked on the background thread immediately afteronPreExecute()
finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also usepublishProgress(Progress...)
to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)
step.
在執行完onPreExecute方法後,立即調用此方法(在非UI線程中),此步驟可以用來進行後台運算,可能會需要較長的時間。前面的參數就是要傳給他的,他接受參數進行處理後,返回的就是Result,不信你看他的返回值。而且他必須返回,然後再把這個返回值傳給最後一步onPostExecute(Result)。
也可以在這個方法中調用publishProgress(Progress...)方法來改變進度。然後用第三步可以更新這些值到UI線程。
onProgressUpdate(Progress...)
, invoked on the UI thread after a call topublishProgress(Progress...)
. The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
在調用publishProgress(Progress...)之後在主線程中調用該方法。他的執行時間沒有定義,該方法用於向用戶顯示progress,同時後台線程仍在運行。
例如,他可以用來動態的更新進度條或日志
onPostExecute(Result)
, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
執行請求。在後台運算完成後調用了用戶UI線程。後台運行的結果以一個參數的形式被傳遞到了這一步。
A task can be cancelled at any time by invokingcancel(boolean)
.可以在任何時間內隨時取消該任務 Invoking this method will cause subsequent(隨後) calls toisCancelled()
to return true. 調用這個方法後,isCancelled()方法將會返回true(這不是廢話嗎)。
After invoking this method,onCancelled(Object)
, instead ofonPostExecute(Object)
will be invoked afterdoInBackground(Object[])
returns.
調用該方法後,在doInBackground(Object[])方法返回結果後,將不會調用onPostExecute(Object)方法接受Result,而是調用onCancelled(Object)方法接受Result。(這裡要等到doInBackground(Object[])方法結束後才能正是取消任務,所以需要使用isCancelled()在doInBackGround中判斷)
To ensure that a task is cancelled as quickly as possible, you should always check the return value ofisCancelled()
periodically fromdoInBackground(Object[])
, if possible (inside a loop for instance.)
為了確保任務可以盡快的取消,如果可以的話,你應該在doInBackground(Object[]中使用isCancelled()檢查一下任務是否被取消了
There are a few threading rules that must be followed for this class to work properly(正常工作):
private class MyTask extends AsyncTask { ... }
The AsyncTask class must be loaded on the UI thread. This is done automatically as ofJELLY_BEAN
. 這個類必須在UI線程上加載The task instance must be created on the UI thread. task實例也必須在UI線程中創建execute(Params...)
must be invoked on the UI thread. execute()也必須在UI線程上Do not callonPreExecute()
,onPostExecute(Result)
,doInBackground(Params...)
,onProgressUpdate(Progress...)
manually.這幾個方法不能手動調用,就像onCreate一樣
The task can be executed only once (an exception will be thrown if a second execution is attempted(嘗試).) 該任務只能被執行一次,第二次嘗試執行會有拋出異常
Service概念及用途:Android中的服務,它與Activity不同,它是不能與用戶交互的,不能自己啟動的,運行在後台的程序,如果我們退出應用時,Service進程
本文實例講述了Android Activity啟動模式之standard。分享給大家供大家參考,具體如下:Android的活動是通過任務Task來進行管理的,一個任務就是
靠譜助手作為國內知名的電腦安卓模擬器,為很多網友所熟知。但靠譜助手的一大诟病就是卡,也沒辦法設置。一個小軟件都能很卡,畫面不流暢、操作也不流暢。結合官方和廣
設計過一款基於開源的XMPP即時通信協議的軟件,采用C/S協議,通過GPRS無線網絡用TCP協議到服務器,以架設開源的Openfire 服務器作為即時通訊平台 系統主要由