我正在开发 android 应用程序并从 php webservice 获取数据。在调用 php webservice 之前,我正在检查互联网连接。如果存在连接,则只有异步任务将启动。但是在这里我遇到了另一个问题,即在检查互联网连接后并在以异步方法执行后台任务时,有时电源突然断电,此时崩溃即将来临。但实际上,如果未执行 try 操作,我使用了一个布尔变量并保持 server=false 。但是,当将参数发布到 php 时没有互联网连接时,它不会捕获方法,因此它不会将 toast 消息显示为“再试一次”。请告诉我实际上我哪里出错了。
My code:
boolean server = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
if (haveNetworkConnection()) {
LongOperation1 op = new LongOperation1();
op.execute("");
} else {
Toast.makeText(getApplicationContext(),
"No Network Connection", Toast.LENGTH_LONG).show();
}
}
private void loadFeed()
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("val1",value1));
postParameters.add(new BasicNameValuePair("val2",value2));
try {
response = CustomHttpClient
.executeHttpPost(
"http://....................../file.php",
postParameters);
System.out.println("the ultimate response" + response);
}
catch (Exception e) {
server = false;
e.printStackTrace();
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
private class LongOperation1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
loadFeed();
return "Executed";
}
@Override
protected void onPostExecute(String result) {
dialog1.dismiss();
try {
if (server) {
Toast.makeText(getApplicationContext(),
"Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Try Again", Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
dialog1 = ProgressDialog.show(Reuse.this, "Please wait...",
"Retrieving data ...", true);
}
@Override
protected void onProgressUpdate(Void... values) {
}
}