非活动类中的AsyncTask中的Toast

时间:2015-02-22 14:49:25

标签: android android-asynctask toast android-context

我有一个非Activity类,其中包含一个调用URL的AsyncTask。 如果由于某些原因导致连接超时,我想通过发布Toast让用户知道这一点。 但我无法获得任何上下文。

如何实现这一目标?

RPIcall.class

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;

class RPicall extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... uri) {

        int timeoutSocket       = 3000;
        int timeoutConnection   = 3000;

        try{

            Log.v("call URL: ", uri[0]);

            HttpGet httpGet = new HttpGet(uri[0]);
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used. 

            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.

            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpResponse response = httpClient.execute(httpGet);

        } catch (ClientProtocolException e) {
            //Here Connection TimeOut excepion
            //Toast.makeText(, "Your connection timedout", Toast.LENGTH_SHORT).show();
            Log.v("Server not Reachable: ", uri[0]);
            publishProgress("TimeOut");

        } catch (HttpHostConnectException e) {

            Log.e("Server not Reachable: ", uri[0]);

        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        String test = "test";
        Log.v("finished: ", test);

    }
}

2 个答案:

答案 0 :(得分:5)

步骤1:向RPicall添加一个Context的构造函数,将其存储在数据成员中。

第2步:使用Context中的onPostExecute()来显示Toast

步骤3:在您创建Context的实例时,传入合适的RPicall

答案 1 :(得分:1)

定义一个构造函数,该构造函数将Context对象作为参数,并将其保留为类成员。例如:

class RPicall extends AsyncTask<String, String, Void> {

       private final Context mContext;
       public RPicall(Context c) {
          mContext = c;
       }

 }