我使用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