簡體   English   中英

需要更多了解android中的AsyncTask

[英]need more understanding of AsyncTask in android

我有這行代碼,這根本沒有問題,唯一的問題是,每次執行此代碼時,應用程序都會等待所有過程完成,從而使接口可能不響應半秒鍾。 我發現最好的解決方案是使用Thread但這會引起一些問題,因此我訴諸於AsyncTask ,但我很難理解。 誰能幫助我如何將其實現到此代碼行?

            ima.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    search.clearFocus();
                    currentItem = ssil;
                    if (currentRoom.equals("None")) {
                        Toast.makeText(StartMoving.this, "Please select a room before adding an item", Toast.LENGTH_LONG).show();
                    }else{

                        try {
                            String currentitemholder = startmoving.getSingleItemName(currentMove, currentRoom, currentItem);
                            if (currentitemholder.equals(currentItem)) {
                                String ssi = startmoving.getSingleItemValue(currentMove, currentRoom, currentItem);
                                String ssiw = startmoving.getSingleItemWeight(currentMove, currentRoom, currentItem);
                                String stw = startmoving.getTotalWeight(currentMove);
                                String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                                String diw = startmoving.getListItemWeight(currentItem);
                                int istw = Integer.parseInt(stw);
                                int isiw = Integer.parseInt(ssiw);
                                int isi = Integer.parseInt(ssi);
                                int isrw = Integer.parseInt(srw);
                                int idiw = Integer.parseInt(diw);
                                currentItemValue = "" + ++isi;
                                currentItemWeight = "" + (isiw + idiw);
                                currentTotalItemWeight = "" + (istw + idiw);
                                currentRoomWeight = "" + (isrw + idiw);
                                currentTotalItem = startmoving.getTotalItem(currentMove) + 1; 
                                startmoving.updateItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                                startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                                startmoving.setTotalItem(currentMove, currentTotalItem);
                                String displayname = startmoving.getItemName(currentMove, currentRoom);
                                String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                roomContent.setText(displayname);
                                itemValue.setText(displayvalue);
                                itemWeight.setText(displayweight);
                                totalweight.setText(displaytotalweight);
                                roomweight.setText(displayroomweight); 
                                int displaytotalitem = startmoving.getTotalItem(currentMove); 
                                totalitem.setText("" + displaytotalitem);
                            }
                        }catch (Exception e) {
                            // TODO Auto-generated catch block
                            currentItemValue = "1";
                            currentItemWeight = ssiw;
                            String stw = startmoving.getTotalWeight(currentMove);
                            String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                            String diw = startmoving.getListItemWeight(currentItem);
                            int istw = Integer.parseInt(stw);
                            int isrw = Integer.parseInt(srw);
                            int idiw = Integer.parseInt(diw);
                            currentTotalItemWeight = "" + (istw + idiw);
                            currentRoomWeight = "" + (isrw + idiw);
                            currentTotalItem = startmoving.getTotalItem(currentMove) + 1; 
                            startmoving.addNewItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                            startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                            startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                            startmoving.setTotalItem(currentMove, currentTotalItem);
                            startmoving.setTotalItem(currentMove, currentTotalItem);
                            String displayname = startmoving.getItemName(currentMove, currentRoom);
                            String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                            String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                            String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                            String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                            roomContent.setText(displayname);
                            itemValue.setText(displayvalue);
                            itemWeight.setText(displayweight);
                            totalweight.setText(displaytotalweight);
                            roomweight.setText(displayroomweight); 
                            int displaytotalitem = startmoving.getTotalItem(currentMove); 
                            totalitem.setText("" + displaytotalitem);
                        }
                    }
                }
            });

            imr.setOnClickListener(new OnClickListener() {

                @SuppressLint("ShowToast")
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    search.clearFocus();
                    currentItem = ssil;
                    if (currentRoom.equals("None")) {
                        Toast.makeText(StartMoving.this, "Please select a room before removing an item", Toast.LENGTH_LONG).show();
                    }else{

                        try {
                            String currentitemholder = startmoving.getSingleItemName(currentMove, currentRoom, currentItem);
                            if (currentitemholder.equals(currentItem)) {
                                String ssi = startmoving.getSingleItemValue(currentMove, currentRoom, currentItem);
                                String ssiw = startmoving.getSingleItemWeight(currentMove, currentRoom, currentItem);
                                String stw = startmoving.getTotalWeight(currentMove);
                                String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                                String diw = startmoving.getListItemWeight(currentItem);
                                int istw = Integer.parseInt(stw);
                                int isiw = Integer.parseInt(ssiw);
                                int isi = Integer.parseInt(ssi);
                                int isrw = Integer.parseInt(srw);
                                int idiw = Integer.parseInt(diw);
                                if (isi > 1) {
                                    currentItemValue = "" + --isi;
                                    currentItemWeight = "" + (isiw - idiw);
                                    currentTotalItemWeight = "" + (istw - idiw);
                                    currentRoomWeight = "" + (isrw - idiw);
                                    currentTotalItem = startmoving.getTotalItem(currentMove) - 1; 
                                    startmoving.updateItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                                    startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                    startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    String displayname = startmoving.getItemName(currentMove, currentRoom);
                                    String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                    String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                    String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                    String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                    roomContent.setText(displayname);
                                    itemValue.setText(displayvalue);
                                    itemWeight.setText(displayweight);
                                    totalweight.setText(displaytotalweight);
                                    roomweight.setText(displayroomweight); 
                                    int displaytotalitem = startmoving.getTotalItem(currentMove); totalitem.setText("" + displaytotalitem);
                                }else{
                                    String sstw = startmoving.getTotalWeight(currentMove);
                                    String ssrw = startmoving.getRoomWeight(currentMove, currentRoom);
                                    int isstw = Integer.parseInt(sstw);
                                    int issrw = Integer.parseInt(ssrw);
                                    currentTotalItemWeight = "" + (isstw - idiw);
                                    currentRoomWeight = "" + (issrw - idiw);
                                    currentTotalItem = startmoving.getTotalItem(currentMove) - 1; startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                    startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom);
                                    startmoving.deleteItem(currentMove, currentRoom, currentItem); startmoving.setTotalItem(currentMove, currentTotalItem);
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    String displayname = startmoving.getItemName(currentMove, currentRoom);
                                    String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                    String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                    String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                    String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                    roomContent.setText(displayname);
                                    itemValue.setText(displayvalue);
                                    itemWeight.setText(displayweight);
                                    totalweight.setText(displaytotalweight);
                                    roomweight.setText(displayroomweight); 
                                    int displaytotalitem = startmoving.getTotalItem(currentMove); 
                                    totalitem.setText("" + displaytotalitem);
                                }   
                            }
                        }catch (Exception e) {
                            // TODO Auto-generated catch block

                        }
                    }
                }
            });

如您所見,這是兩個按鈕,它們調用數據庫(發送和接收數據)並將其顯示到GUI。

編輯

感謝您的精彩回復! 在確定正確答案之前,我將首先學習AsyncTask。 仍然需要處理您給我的所有這些信息。

編輯忘了提到起步是我的數據庫模塊

如果您執行長時間的操作,例如加載文件或訪問數據,則Android應用程序的用戶界面將阻塞,直到相應的代碼完成為止。

異步任務

為了使用AsyncTask類,您必須擴展它並至少重寫doInBackground()方法。

您將需要實現的最常見方法是:

   1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

   2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

   3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().

   4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

現在,在代碼選擇中,您可以做什么。

所有數據庫操作和數據操作代碼均以doInBackground(Params…)方法編寫,並以onPostExecute(Result)方法顯示數據。

謝謝。

AsyncTask在另一個線程內的doInBackground()執行所有操作,該線程無法訪問您的視圖所在的GUI。

preExecute()postExecute()使您可以在此新線程發生繁重之前和之后訪問GUI,您甚至可以將long操作的結果傳遞給postExecute() ,然后顯示任何處理結果。

Android通過一個線程(即所謂的UI線程)修改用戶界面。 如果直接在UI線程上執行長時間運行的操作(例如,從Internet下載文件),則應用程序的用戶界面將“凍結”,直到完成相應的任務為止。 發生這種情況時,用戶很容易感覺到您的應用程序很慢。

通過AsyncTask,可以正確,輕松地使用UI線程。 此類允許執行后台操作並在UI線程上發布結果,而無需操縱線程和/或處理程序。

  1. onPreExecute() –在線程開始運行之前在UI線程上調用。 此方法通常用於設置任務,例如通過顯示進度條。

  2. doInBackground(Params…) –這是在后台線程上運行的方法。 在這種方法中,應將希望應用程序執行的所有代碼放在后台。 參考我們的簡單RSS應用程序,您將在此處放置下載XML提要並進行解析的代碼。 在onPreExecute()之后立即調用doInBackground()。 完成后,它將結果發送到onPostExecute()。

  3. onProgressUpdate() -在doInBackground()中調用publishProgress()時調用。

  4. onPostExecute(Result) –后台線程完成后在UI線程上調用。 它將從doInBackground()接收到的結果作為參數。

AsyncTask是一個通用類,它使用3種類型:AsyncTask。

Params – the input. what you pass to the AsyncTask
Progress – if you have any updates, passed to onProgressUpdate()
Result – the output. what returns doInBackground()

創建任務后,可以像下面這樣執行:

new DownloadTast().execute(url1, url2, urln);

這是AsyncTask的一個示例

好的,沒有給您解決方案,我認為最好是開始閱讀有關Android中異步請求的信息: http : //developer.android.com/reference/android/os/AsyncTask.html 了解Web的異步性質將有助於您理解UI與可能呈現的數據的分離。

響應能力是您要將UI與數據分離的第一大原因。 對於使用EDT(事件疏散線程)的Java Swing開發人員,這可能是最好的解釋: http ://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html。 有許多慢速應用程序的示例,開發人員會將長時間運行的進程附加到其按鈕或其他任何東西上,然后嘗試使用自己的線程來修復它以加快處理速度。 Swing最終使用SwingWorker和doInBackground()在Java 6中修復了此問題。 對於要使用Android的Swing開發人員,他們可能會看一下AsyncTask並詢問,為什么Java這么簡單?

因此,花一些時間來熟悉AsyncTask,了解如何使用它,如何將其與Listeners結合使用以獲得更大的靈活性,然后您將了解如何更改代碼。

如果您需要其他幫助,請告訴我們正確的方向。

基本上,您需要擴展AsyncTask類並進行自己的實現。 您可以利用doInBackground()函數在非UI線程中運行的事實,並且返回的結果可以在UI線程中運行的onPostExecute()函數中使用。

您提到您的代碼調用了數據庫,所以我將假設您的“ startmoving”對象是數據庫模塊。 在下面的示例代碼中,我將其稱為MovingDb類,因為在您的代碼中沒有顯示實際的類名是什么。

// this will hold all your calculated value
private class DisplayInfo {
   String displayName, displayValue, displayWeight, displayTotalWeight, displayRoomWeight;
   int displayTotalItem;
}

private class ItemHolderTask extends AsyncTask<MovingDb, Integer, DisplayInfo> {

   protected DisplayInfo doInBackground(MovingDb... movingDbs) {
      // this code runs in background thread so do your DB work here
      if (movingDbs != null && movingDbs.length > 0 && movingDbs[0] != null) {
         MovingDb startMoving = movingDbs[0];
         // move all your db operations here
         String currentItemHolder = startMoving.getSingleIteName(....)
         // blah blah
         DisplayInfo displayInfo = new DisplayInfo();
         displayInfo.displayName = startMoving.getItemName(...);
         displayInfo.displayValue = startMoving.getItemValue(...);
         // set up the rest of your display info values
         return displayInfo;
      }
   }

   protected void onPostExecute(DisplayInfo displayInfo) {
      // the displayInfo you return from doInBackground comes here
      if (displayInfo != null) {
         roomContent.setText(displayInfo.displayName);
         itemValue.setText(displayInfo.displayValue);
         // and so on...
      }
   }
}

在onClick函數中,您只需啟動ItemHolderTask:

new ItemHolderTask().execute(startMoving);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM