我使用AlertDialog(不是活动)通知用户需要网络连接并带有一个选项,以将其连接到网络设置(启用移动/ wi-fi)连接。如果他们选择单击“取消”,而是强制完成主要活动()。
检查主活动onResume()中的网络连接,并且如果没有连接,则调用CreateNetErrorDialog()...不可能使用BACK来关闭对话框 - 仅取消杀死主要活动的对话框。
例...
protected void CreateNetErrorDialog(String errorMessage) {
Log.d(TAG, "CreateNetErrorDialog() entered...");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(errorMessage)
.setTitle("Unable to connect")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyMainActivity.this.finish();
}
}
);
AlertDialog alert = builder.create();
alert.show();
Log.d(TAG, "Exiting CreateNetErrorDialog()...");
}
编辑:调用CreateNetErrorDialog从您的AsyncTask的onPostExecute()方法 - 它运行在UI线程(doInBackground没有)。从我自己的代码示例...
private class FileDownloader extends AsyncTask<String, Void, Void> {
private Boolean Success = false;
private String ResultString = "";
@Override
protected Void doInBackground(String... params) {
try {
// Do whatever
}
catch (Exception e) { // <-- Use the correct exception type
ResultString = "Some error message";
}
}
@Override
protected void onPostExecute(Void result) {
if (!Success)
CreateNetErrorDialog (ResultString);
else
// Do whatever
}
}
显示在您检查网络并启动该活动的代码 – ingsaurabh
看到这个: 尝试{\t \t androidHttpTransport =新HttpTransportSE(URL,30000); \t \t androidHttpTransport.call(SOAP_ACTION,envelope); \t \t so =(SoapObject)envelope.bodyIn; \t \t String st = so.toString(); //做一些处理..... } 赶上(例外五) \t \t { \t \t Log.i( “没有互联网”,e.getMessage()); \t \t this.cancel(true); \t \t Intent intent = new Intent(context,NetworkErrorActivity.class); \t \t startActivity(intent); \t \t \t \t} –
是每一个日志打印的时间,如果是,那么有一些例外,这并不是网络,而是使捕捞代码每次运行时使调试代码的任何异常 – ingsaurabh