致命异常:AsyncTask#1,如果激活飞行模式

时间:2018-01-11 16:18:06

标签: java android android-asynctask fatal-error

我使用AsyncTask来获取我的服务器的请求。 如果我连接到互联网,Everythink工作正常,但如果我激活飞机模式,我会得到致命的异常:

01-11 16:01:56.602 3456-3456/com.me.myapp E/ApiHelper: Error at 
getting WuerdestDu Stats. Id: 19
01-11 16:01:56.603 3456-3522/com.me.myapp E/AndroidRuntime: FATAL 
EXCEPTION: AsyncTask #1
                                                               Process: com.me.myapp, PID: 3456

奇怪的是,这是在详细模式下Logcat的完整错误日志,没有过滤器。

这是我使用AsyncTask的地方:

try {
    response = new ApiGetHelper().execute(path).get();
} catch (Exception e) {
    Log.e(TAG, "Error at getting WuerdestDu Stats. Id: " + question.getId(), e);
}

这是我的AsyncTask:

public class ApiGetHelper extends AsyncTask<String, String, String> {
private final static String TAG = ApiGetHelper.class.getSimpleName();

@Override
protected String doInBackground(String... strings) {
    String urlString = strings[0];

    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        int responseCode = urlConnection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            Log.i(TAG, "Response: " + urlConnection.getResponseCode() + ": " + urlConnection.getResponseMessage());
        } else {
            Log.e(TAG, "Response: " + urlConnection.getResponseCode() + ": " + urlConnection.getResponseMessage());
        }

        return ApiUtils.readResponseAsString(urlConnection.getInputStream());
    } catch (MalformedURLException e) {
        throw new IllegalStateException("URL-ERROR", e);
    } catch (IOException e) {
        throw new IllegalStateException("IO-ERROR", e);
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果您打开飞机模式,您将失去互联网,您需要在尝试发布到服务器之前检查是否有可用的互联网连接。

以下内容应该可以解决问题

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }

参考:Android check internet connection