【发布时间】:2017-01-18 08:50:31
【问题描述】:
我有一个应用程序,它有一个Asynctask 用于 Web Api 请求,并且有很多选项卡的请求。
当用户在标签之间快速滚动时,许多请求午餐!但是当用户关闭 Activity 时,一些正在进行的后台操作会导致应用崩溃。
我试过这个: 在我的 doinBackground 中,我总是检查片段是否为 isAdded()
@Override
protected Void doInBackground(Void... Params) {
Bundle bundle = getArguments();
String url = ServiceHandler.serverEnum.serverRootPath + ServiceHandler.serverEnum.Me.toString();
if(isAdded()){
response = StaticUtils.generateReguest(mContext, url, headerParams, bodyParams, URLParams, null, ServiceHandler.serviceMethod.get.toString());
}
return null;
}
当 Asynctask 从 Activity 运行时,我也会这样做:
onStop 活动我取消了运行的 Asyctask 然后onPostExecute 检查是否未取消做一些 UI 工作。但问题是我在doInBackground 中崩溃了。
这是在StaticUtils.generateReguest 中创建响应时发生崩溃的那一行:
if (status != 200 && status != 401 && status != 404 && status != 0) {
Intent intent = new Intent(context, ErrorActivity.class); //error point to this line
intent.putExtra(ErrorActivity.REASON, "SERVER");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
(context).startActivity(intent);
}
这是导致上述行的日志猫:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
我认为这可能是因为上下文。因为当我生成一个请求时,我将 Activity 上下文传递给 Requestgenerator 并且有时正如您在代码中看到的那样,它会导致显示错误活动。当用户关闭活动上下文时,请求生成器无法打开`ErrorActivity。处理此问题的最佳做法是什么?我用谷歌搜索,找不到好的解决方案?
【问题讨论】:
-
你也应该在 onPause of activity 中做同样的事情。
-
doingOnBackground 发生崩溃!
-
你能把日志给我吗
-
你在哪里使用
context.getPackageName()? -
没有,但它指向这一行:Intent intent = new Intent(context, ErrorActivity.class);
标签: android android-asynctask crash request android-context