简体   繁体   中英

Android - How to show Toast on ConnectionTimeout

I have the following problem: My app uses a function which executes all HTTP calls. As a quick fix I'd like to show the user a toast message whenever there is an ConnectionTimeout .

The problem is that this executeHttp() is called from several AsyncTasks and I can't figure out how to get the required context .

I read something about runOnUiThread but this also didn't seem to work for me...

Any ideas?

Thanks!

Update:

I'd like to have a solution which I can use in my executeHttp() function because else I have do add this code in 100 different places... Is this possible?

First, implement a Method to show a Toast to your activity:

class MyActivity extends Activity {
// some stuff

    public void showToast(String text, int duration) {
        Toast toast = Toast.makeText(this.getBaseContext(), text, duration);
        toast.show();
    }
}

The let your AsyncTask hold a reference to the activty which can then be called in the onProgressUpdate Method:

class MyAsyncTask extends AsyncTask {

    MyActivity activity;

    public MyAsyncTask(MyActivity a)
        this.activity = a;
    }

    @Override
    protected Object doInBackground(String... params) {
        try {       
            // do your stuff here

        } catch (ConnectionTimeoutException e) {
            publishProgress("timeout");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        if(values[0].equals("timeout")
            activity.showToast("Ups, we have a timeout!", Toast.LENGTH_LONG); }
        }
    }
}

EDIT ------------

If you want it in your executeHttp() method, you have to pass the Context to it in order to show a Toast:

public ReturnValue executeHttp(Context context) {
    try {
        // ...
    } catch(ConnectionTimeoutException e) {
        Toast t = Toast.makeToast(context, message, duration);
        t.show();
    }
}

summary: no available context -> no toast

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM