有没有什么办法可以在Activity onDestroy事件上ping一个url。我曾尝试使用AsyncTask,因为一些教程表示它将在onDestroy之后执行,但它不起作用。Android需要ping url onDestroy事件
这是在课堂上,我平毁
public class inactive extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
String res = new String();
try {
BufferedReader reader = null;
URLConnection uc = null;
try {
URL urll = new URL(new StringBuilder()
.append("www.myuru.com").toString());
uc = urll.openConnection();
uc.connect();
reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
res = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
,这是从我的活动中的onDestroy方法
@Override
protected void onDestroy() {
new inactive(this, sharedpreferences).execute();
super.onDestroy();
}
我的测试表明,这种代码中断时它试图打开连接(urll.openConnection())。
我已经试过线程,异步任务和syncronously调用带有多种方法,如网址:URLConnection的,HTTPGET
请发布您用于ping网址的代码。 –