简体   繁体   English

Android-如何在ConnectionTimeout上显示Toast

[英]Android - How to show Toast on ConnectionTimeout

I have the following problem: My app uses a function which executes all HTTP calls. 我有以下问题:我的应用程序使用了一个执行所有HTTP调用的函数。 As a quick fix I'd like to show the user a toast message whenever there is an ConnectionTimeout . 作为快速解决方案,我想在有ConnectionTimeout时向用户显示敬酒消息。

The problem is that this executeHttp() is called from several AsyncTasks and I can't figure out how to get the required context . 问题是该executeHttp()是从多个AsyncTasks调用的,我不知道如何获取所需的context

I read something about runOnUiThread but this also didn't seem to work for me... 我读到一些有关runOnUiThread但这似乎对我也不起作用。

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? 我想要一个可以在我的executeHttp()函数中使用的解决方案,因为否则我确实将代码添加到了100个不同的地方...这可能吗?

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: 让您的AsyncTask持有对活动的引用,然后可以在onProgressUpdate方法中调用该活动:

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: 如果要在executeHttp()方法中使用它,则必须将Context传递给它以显示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 摘要:无可用上下文->无吐司

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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