如何在Java中执行AsyncTask子类?

时间:2013-11-28 10:14:20

标签: android callback android-asynctask subclass

我正在尝试学习如何调用嵌套在另一个类中的AsyncTask。

A类(AsyncTask是子类的类)。 B类(是mainActivity)。

在A组:

我创建了一个接口,其中包含AsyncTask完成时的方法(为了CallBack)。

在B组:

我如何调用我的AsyncTask。看起来像制作实例的正常方式然后.execute()不起作用!我收到以下错误:

No enclosing instance of type NetConnectivity is accessible. Must qualify the allocation with an enclosing instance of type
     

NetConnectivity(例如x.new A(),其中x是。的实例   NetConnectivity)。

在此上下文中,NetConnectivity是A类。

感谢您的时间。

编辑----

这是NetConnectivity类:

public class NetConnectivity {


    public boolean CheckNetworkAvailability(Context context){

        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        String tag = "NetworkCheck";
        if(networkInfo != null && networkInfo.isConnected()){
            Log.i(tag, "Network is available");
            return true;
        } else {
            Log.i(tag, "Network is not available");
            return false;
        }
    }

    public interface WebServiceAsyncListener {
        void WebServiceDone();
    }

    public static class WebServiceAsync extends AsyncTask <String, Integer, Double>{

        private WebServiceAsyncListener wListener;

        public WebServiceAsync(Activity act){
            wListener = (WebServiceAsyncListener) act;
        }

        @Override
        protected Double doInBackground(String... params) {
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(String result) {
          wListener.WebServiceDone();
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://somewebsite.com/receiver.php");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
        }
    }

}

1 个答案:

答案 0 :(得分:3)

使AsyncTask成为“静态”类。