【问题标题】:FATAL EXCEPTION: AsyncTask #1, if airplane mode is activated致命异常:AsyncTask #1,如果激活了飞行模式
【发布时间】:2018-01-11 16:18:06
【问题描述】:

我使用 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);
}

这是我的异步任务:

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);
    }
}
}

【问题讨论】:

  • 您只需要检查一下,您的应用程序是否连接到网络。如果不向用户或其他任何内容显示消息,如果是,则执行您的任务。
  • 离题评论...使用AsyncTask.get 是一个糟糕的主意...事实上,如果您使用get,为什么在地狱中您确实首先使用AsyncTask,因为get 使AsyncTask 同步(如果原因是 NetworkOnMainThreadException,那么您可以禁用防护 - 因为两种解决方案(AsyncTask.get 和禁用防护)都以同样的方式很糟糕 - 应该避免)
  • 是的。你不应该使用 .get()。然后你不应该让 doInBackground() 捕获异常时抛出异常。只需返回 e.getMessage() 然后在 onPostExecute() 的 Toast() 中显示信息。

标签: java android android-asynctask fatal-error


【解决方案1】:

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

类似下面的东西应该可以解决问题

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

  return cm.getActiveNetworkInfo() != null;
 }

参考:Android check internet connection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2015-07-16
    • 2015-07-12
    相关资源
    最近更新 更多