簡體   English   中英

如何在Android中管理異步任務

[英]How to manage async task in Android

在我的活動中,我使用線程來調用服務器,並接收放置在內部存儲器上的XML響應。

調用之后,我讀取了該xml文件以對其進行解析,並向用戶顯示有關該xml文件的信息,但是當我在InputStream中添加此文件時,此InputStream為null。

我想我的活動將繼續簡單的執行,而不必等待線程,所以當我創建InputStream時,我的xml文件不存在。

我使該架構與程序的執行相對應:

此處的架構

如何讓我的活動等待線程結束? 我知道凍結主要活動不是一件好事,但我不知道該怎么做。 我可以添加一個等待進度條,直到線程結束時線程上有觀察者嗎?

PS:我的線程實現了Runnable

/ *************使用解決方案進行編輯************* /

首先,感謝大家的回應,這使我進步了很多。

//In my Activity

MyAsyncTask asyncTask = new MyAsynctask();
asynctask.execute();

//My Async class
public class MyAsynctask extends AsyncTask<Void,Void,Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(getApplicationContext(), "calling server...", Toast.LENGTH_LONG).show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        //Instance of calling class
        //Method of this instance to call the server and create a file in internal storage 
        //After that my file is stored with the server response
        return null;
    }


    @Override
    protected void onPostExecute(Void result){
        super.onPostExecute(result);

        Toast.makeText(getApplicationContext(), "Data received", Toast.LENGTH_LONG).show();

        FileInputStream inputStream = null;
        inputStream = openFileInput("myFile");                     

        data=XMl.parse(inputStream);                  
    }
}

希望這篇文章和您的回復對您有所幫助。

我還認為使用AsnycTask將適合您的用例。

您可以執行AsyncTask並繼續在onPostExecute讀取和解析響應。

干杯! :D

在您的Activity (或Fragment或...) 使用AsyncTask這樣的對象。 我通常實現一個AsyncResponse接口,以更輕松地在不同的Activity中重用AsyncTask:

    MyAsyncTask m = new MyAsyncTask(randomparameters, new AsyncResponse(){
                @Override
                public void onSuccess(Object result) { 
                    // Success!! do what you want
                }

                @Override
                public void onError() { 
                   // Manage errors here
                }
            });
    m.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

如果您使用m.execute()而不是executeOnExecutor,並且同時具有多個AsyncTask,則它們會順序執行;如果您使用executor,則它們將並行執行。 做您想要或需要的。

AsyncTask類 ,它具有其他可以覆蓋的方法,例如onPreExecute等。

public class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {

    private AsyncResponse response;

    public MyAsyncTask(randomparameters, AsyncResponse response) {
        // Constructor
        this.response = response;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // Implements your async code (call your server)
    }

    @Override
    protected void onPostExecute(Boolean result) {
            if (result) {
                // Here you can return the response of the server to the activity
                response.onSuccess(response);
            } else {
                response.onError();
            }
        }
    }

這是接口 (當然,您可以自定義方法):

public interface AsyncResponse {

    void onSuccess(Object result);
    void onError();

}

關於AsyncResponse接口的所有信息都是可選的,但我始終會實現它,並且對我有很大幫助。

 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new DownloadfromInternet().execute(server_url);

        }

//異步任務類類DownloadFromInternet擴展了AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Shows Progress Bar Dialog and then call doInBackground
    }

    // Download  File from Internet
    @Override
    protected String doInBackground(String... f_url) {

        try {
        //make server call and store file in local
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return LOCAL_FILE_NAME;
    }


    @Override
    protected void onPostExecute(String local_file_url) {
        // read local_file_url

    }
}

讓您的活動一直等到執行結束不是一個好主意,因為它將凍結ui線程。 如果任務太長會拋出ANR。 您有2個選擇:

  1. 創建異步任務所需的參數和條件,然后調用它,前提是異步任務是您活動中的內部類,請執行其余操作,這些操作取決於異步任務,從而導致異步任務的onPostExecute回調。

  2. 創建一個接口,該接口的方法可以幫助您將異步任務的結果傳達給實現類。 這是測試和/或使異步任務作為外部類的最佳方法。 我相當多地使用了這種方法。 在異步任務中定義公共方法以將偵聽器設置為您的接口。使您的活動實現該接口。 異步任務完成后,如果listener不為null,則在onPostExecute中調用接口方法。 在活動中的已實現方法中,實現與異步任務結果相關的邏輯。

如果要對其進行測試,則為異步任務設置接口回調總是一個好主意。

我想我的活動將繼續簡單的執行,而不必等待線程,因此在創建InputStream時,我的xml文件不存在。

-正確

對於您的情況,我建議您在觸發請求時可以啟動加載對話框。 當您收到響應時,將結果發送到在UI線程上運行的處理程序,覆蓋它的handleMessage方法,在此您可以關閉對話框並顯示信息。

或者,使用AsynTask,這更加方便。

暫無
暫無

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

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