【发布时间】:2011-10-24 15:55:42
【问题描述】:
伙计们,
我通过这样的代码 sn-p 在 onCreate 的顶部捕获未处理的 Android 异常:
try {
File crashLogDirectory = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + Constants.CrashLogDirectory);
crashLogDirectory.mkdirs();
Thread.setDefaultUncaughtExceptionHandler(new RemoteUploadExceptionHandler(
this, crashLogDirectory.getCanonicalPath()));
} catch (Exception e) {
if (MyActivity.WARN) Log.e(ScruffActivity.TAG, "Exception setting up exception handler! " + e.toString());
}
我想为我在我的 android 应用程序中使用的大约两打 AsyncTask 提供类似的东西,以便捕获并记录 doInBackground 中发生的未处理异常。
问题是,因为 AsyncTask 采用任意类型的初始化器,我不确定如何声明一个超类,我的所有 AsyncTask 都从该超类继承来设置这个未处理的异常处理程序。
谁能推荐一个好的设计模式来处理 AsyncTask 的 doInBackground 方法中未处理的异常,它不涉及为每个新的 AsyncTask 定义复制和粘贴上述代码?
谢谢!
更新
这是我在仔细查看source of AsyncTask之后使用的设计模式
import java.io.File;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public abstract class LoggingAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
protected void setupUnhandledExceptionLogging(Context context) {
try {
File crashLogDirectory = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + Constants.CrashLogDirectory);
crashLogDirectory.mkdirs();
Thread.setDefaultUncaughtExceptionHandler(new RemoteUploadExceptionHandler(
context, crashLogDirectory.getCanonicalPath()));
} catch (Exception e) {
if (MyActivity.WARN) Log.e(ScruffActivity.TAG, "Exception setting up exception handler! " + e.toString());
}
}
}
然后我将我的任务定义如下:
private class MyTask extends LoggingAsyncTask<Void, Void, HashMap<String, Object>> {
protected HashMap<String, Object> doInBackground(Void... args) {
this.setupUnhandledExceptionLogging(MyActivity.this.mContext);
// do work
return myHashMap;
}
}
显然,您的任务可以采用此模式所需的任何参数。您可以定义 RemoteUploadExceptionHandler 来执行必要的日志记录/上传。
【问题讨论】:
-
我已经接受了所有我认为有很好答案的问题...
标签: java android exception android-asynctask unhandled-exception