關(guān)于UncaughtExceptionHandler
轮蜕,它是Java Thread類中定義的一個(gè)接口悦施;用于處理未捕獲的異常導(dǎo)致線程的終止(注意:catch了的是捕獲不到的
)膀跌,當(dāng)我們的應(yīng)用crash的時(shí)候号俐,就會(huì)走UncaughtExceptionHandler
的uncaughtException
方法杯拐,在該方法中可以獲取到異常的信息,我們通過setDefaultUncaughtExceptionHandler
該方法來設(shè)置線程的默認(rèn)異常處理器血巍,將異常信息保存到本地或者是上傳到服務(wù)器萧锉,方便我們快速的定位問題;下面是一個(gè)簡單CrashHandler
的代碼:
public class CrashHandler implements Thread.UncaughtExceptionHandler
{
private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private static final String FILE_NAME_SUFFIX = ".trace";
private static CrashHandler sInstance = new CrashHandler();
private Thread.UncaughtExceptionHandler mDefaultCrashHandler;
private Context mContext;
private CrashHandler()
{
}
public static CrashHandler getInstance()
{
return sInstance;
}
public void init(@NonNull Context context)
{
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
/**
* 當(dāng)程序中有未被捕獲的異常述寡,系統(tǒng)將會(huì)調(diào)用這個(gè)方法
*
* @param t 出現(xiàn)未捕獲異常的線程
* @param e 得到異常信息
*/
@Override
public void uncaughtException(Thread t, Throwable e)
{
try
{
//保存到本地
exportExceptionToSDCard(e);
//下面也可以寫上傳的服務(wù)器的代碼
} catch (Exception e1)
{
e1.printStackTrace();
}
e.printStackTrace();
//如果系統(tǒng)提供了默認(rèn)的異常處理器柿隙,則交給系統(tǒng)去結(jié)束程序,否則就自己結(jié)束自己
if (mDefaultCrashHandler != null)
{
mDefaultCrashHandler.uncaughtException(t, e);
} else
{
Process.killProcess(Process.myPid());
}
}
/**
* 導(dǎo)出異常信息到SD卡
*
* @param e
*/
private void exportExceptionToSDCard(@NonNull Throwable e)
{
//判斷SD卡是否存在
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
return;
}
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
File file = new File(PATH + File.separator + time + FILE_NAME_SUFFIX);
try
{
//往文件中寫入數(shù)據(jù)
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(time);
pw.println(appendPhoneInfo());
e.printStackTrace(pw);
pw.close();
} catch (IOException e1)
{
e1.printStackTrace();
} catch (PackageManager.NameNotFoundException e1)
{
e1.printStackTrace();
}
}
/**
* 獲取手機(jī)信息
*/
private String appendPhoneInfo() throws PackageManager.NameNotFoundException
{
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
StringBuilder sb = new StringBuilder();
//App版本
sb.append("App Version: ");
sb.append(pi.versionName);
sb.append("_");
sb.append(pi.versionCode + "\n");
//Android版本號(hào)
sb.append("OS Version: ");
sb.append(Build.VERSION.RELEASE);
sb.append("_");
sb.append(Build.VERSION.SDK_INT + "\n");
//手機(jī)制造商
sb.append("Vendor: ");
sb.append(Build.MANUFACTURER + "\n");
//手機(jī)型號(hào)
sb.append("Model: ");
sb.append(Build.MODEL + "\n");
//CPU架構(gòu)
sb.append("CPU: ");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
sb.append(Arrays.toString(Build.SUPPORTED_ABIS));
} else
{
sb.append(Build.CPU_ABI);
}
return sb.toString();
}
}
上面代碼是當(dāng)應(yīng)用發(fā)生crash時(shí)鲫凶,判斷SD是否存在禀崖,然后拿到設(shè)備信息和異常信息保存到SD卡根路徑.trace文件中;最后將異常交給系統(tǒng)處理螟炫,如果沒有設(shè)置默認(rèn)的異常處理波附,就自行終止應(yīng)用。
Tips:涉及到SD卡,記得在Manifest中添加權(quán)限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
在Application中初始化CrashHandler
public class App extends Application
{
@Override
public void onCreate()
{
super.onCreate();
CrashHandler.getInstance().init(this);
}
}
下面我們手動(dòng)拋出異常掸屡,然后查看SD卡下的異常信息
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//Android M 權(quán)限申請(qǐng)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
private void initView()
{
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if (v == mButton)
{
throw new RuntimeException("自定義異常");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if (requestCode == 0)
{
for (int grantResult : grantResults)
{
if (grantResult == PackageManager.PERMISSION_DENIED)
{
Toast.makeText(this, "write_external_storage denied封寞!", Toast.LENGTH_SHORT).show();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
下面就是保存的設(shè)備信息和異常信息
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者