1.全局捕获异常可以自己创建crashHandler
实现Thread.UncaughtExceptionHandler
,并在Application
初始化里面设置这个crashHandler
,代码如下:
public class CarshHandler implements Thread.UncaughtExceptionHandler{
private Context context;
private static final boolean DEBUG = true;
private static CarshHandler carshHandler;
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
private CarshHandler() {
}
public static CarshHandler getInstance(){
if(carshHandler==null){
synchronized (CarshHandler.class){
if(carshHandler==null){
carshHandler = new CarshHandler();
}
}
}
return carshHandler;
}
public void init(Context context){
uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
this.context = context.getApplicationContext();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, final Throwable e) {
if(uncaughtExceptionHandler !=null && !DEBUG){
uncaughtExceptionHandler.uncaughtException(t,e);
}else{
//获取异常信息,这里是弹出弹窗,也可以做其他操作,比如写日志等等
final StringBuilder builder = new StringBuilder();
StackTraceElement[] trace = e.getStackTrace();
builder.append(e.getMessage());
builder.append("\nat ");
builder.append(trace[0]);
//必须新开线程,否则弹不出弹窗
new Thread(new Runnable() {
@Override
public void run() {
//必须初始化looper,否则AlertDialog无法初始化handler
Looper.prepare();
Dialog dialog = new .Builder(context)
.setTitle("程序异常")
.setMessage(builder.toString())
.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Process.killProcess(Process.myPid());
}
})
.create();
//ApplicationContext必须用系统级window,Androidmanifest也要声明权限
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
dialog.show();
Looper.loop();
}
}).start();
}
}
}
在Application
的onCreate
方法里加下面两句代码:
CarshHandler carshHandler = CarshHandler.getInstance();
carshHandler.init(this);
2.Android
中单个dex
文件最大方法数为65536,大型应用可能会出现方法数越界的问题。Android
提供了multidex
方案,使用有两种方法:让应用的application
继承MultiDexApplication
;重写Application
的attachBaseContext
方法,在里面加Multidex.install(this)
。multidex可
能存在的问题:
(1)启动速度降低,甚至出现ANR
,尽量避免生成较大的dex
文件。
(2)无法兼容4.0及以下,同时可能会出现大量消耗内存的情况,导致应用崩溃。
3.动态加载技术也叫插件化技术,用来实现热插拔即热更新。它需要解决三个问题:资源访问;Activity
的生命周期管理;插件ClassLoader
的管理。
网友评论