我正试图学习如何调用嵌套在另一个类中的AsyncTask。如何在Java中执行AsyncTask子类?
A类(AsyncTask是子类的类)。 B类(主要活动)。
在A类:
我创建包含用于当所述的AsyncTask是成品的方法(回叫的缘故)的接口。
B类:
我该如何去调用我的AsyncTask。看起来像制作实例的正常方式,然后.execute()不起作用!我收到以下错误:
No enclosing instance of type NetConnectivity is accessible. Must qualify the allocation with an enclosing instance of type
NetConnectivity (e.g. x.new A() where x is an instance of 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) {
}
}
}
}
你能提供一些代码吗?如果你会提供我可以告诉一些解决方案。 – Sajmon
@Geralt,我刚刚添加了包含AsyncTask的类。感谢您的答复。 – Kourosh