簡體   English   中英

在AsyncTask中顯示Toast

[英]Show Toast inside AsyncTask

  public class ayncClass extends AsyncTask<String, Void, String> {

        public void onPreExecute(){


        }
        @Override
        protected String doInBackground(String... params) {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(URL HERE);
            try{
                HttpResponse responseGiven = client.execute(get);
                StatusLine statusLine = responseGiven.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if(statusCode == 404){
                    Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();

                }
            } catch(Exception e){

            }
            return null;
        }

        public void onPostExecute(...){
            super.onPostExecute(s);

        }

    }

但是,當我調試並運行該應用程序時,它確實會顯示Toast。 有沒有辦法在AsyncTask工作時對其進行操作?

謝謝!

Toast屬於UI。

我們只能在主線程(UI線程)中更新UI。

永遠不會在主線程中調用AsyncTask.doInBackground() ,這就是原因。

您應該從這里使用我的代碼:

public enum Toaster {
    INSTANCE;

    private final Handler handler = new Handler(Looper.getMainLooper());

    public void showToast(final Context context, final String message, final int length) {
        handler.post(
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, length).show();
                }
            }
        );
    }

    public static Toaster get() {
        return INSTANCE;
    }
}

那你可以做

Toaster.get().showToast(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT);

這將在UI線程上運行您的代碼,並且將起作用。

這可能會有所幫助

onPreExecute(){//一些代碼#1}

 doInBackground() { runOnUiThread(new Runnable() { public void run() { // some code #3 (Write your code here to run in UI thread) } }); } onPostExecute() { // some code #3 } 

Toast是UI元素,它不會出現,因為您的應用程序的UI在UI線程上運行,而AsyncTask doInBackground方法在不同的線程上運行。 因此,您要執行的與UI相關的任何操作都應該在onPostExecuteonPreExecute 如果存在這種情況,您必須在doInBackground更新UI, doInBackground可以使用處理程序線程或最佳方式,可以使用runOnUiThread方法,並且可以在其中添加吐司。

嘗試下面

public class ayncClass extends AsyncTask<String, Void, String> {

    public void onPreExecute(){


    }
    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 404){
                // Toast.makeText(getApplicationContext(), "ERROR", //Toast.LENGTH_SHORT).show();

            }
        } catch(Exception e){

        }
        return String.valueOf(statusCode ); // make this change
    }

    public void onPostExecute(String result){
        super.onPostExecute(s);
 Toast.makeText(getApplicationContext(), result, 
 Toast.LENGTH_SHORT).show();
    }

}

將Toast消息始終放置在PostExecute方法中。

公共無效onPostExecute(...){super.onPostExecute(s;

    Toast.makeText(context, "Hellooo I am at Post Execute method", Toast.LENGTH_SHORT).show();
    }

只能從UI線程顯示Toast 在UI線程中調用了onPostExecute ,因此您可以將statusCode存儲在成員變量中,並在onPostExecute方法中檢查404,然后在onPostExecute顯示Toast 像這樣:

public class ayncClass extends AsyncTask<String, Void, String> {

    private int mStatusCode;

    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            mStatusCode = statusLine.getStatusCode();
        } catch(Exception e){
            // do NOT let catch blocks without log
            // if something bad happens you will never know
        }
        return null;
    }

    public void onPostExecute(...){
        super.onPostExecute(s);
        if(mStatusCode == 404){
            Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
        }
    }
}

或者只是將狀態代碼作為參數傳遞給onPostExecute:

public class ayncClass extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            return statusLine.getStatusCode();
        } catch(Exception e){
            // do NOT let catch blocks without log
            // if something bad happens you will never know
        }
        return -1;
    }

    public void onPostExecute(Integer statusCode){
        super.onPostExecute(s);
        if(statusCode == 404){
            Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
        }
    }
}

僅當您必須向UI線程中顯示某些內容(例如Toast消息)時,然后編寫:

runOnUiThread(new Runnable(){
    public void run() {
        //Interaction with UI (Toast message)
    }
});

您無法在doInBackground函數中顯示吐司,因為doInBackground函數不適用於UI線程。 您可以將進度發布到onProgressUpdate函數。 它將在UI Thread上工作。

public class ayncClass extends AsyncTask<String, Void, String> {

    private final Context context;

    public ayncClass(Context context) {
        this.context = context;
    }

    public void onPreExecute(){


    }
    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(stat-usCode == 404){
            // you can not use toast in doInBackground function. you need to pass to progress
            publishProgress(0);
            }
        } catch(Exception e){

        }
        return null;
    }

    @Override
        protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show();
        }

    public void onPostExecute(...){
        super.onPostExecute(s);

    }

}

暫無
暫無

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

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