精华内容
下载资源
问答
  • 1. 创建类继承 UncaughtExceptionHandlerimport android.content.Context;import android.os.Environment;import android.os.Looper;import android.text.TextUtils;import android.util.Log;import android.widget....

    1. 创建类继承 UncaughtExceptionHandler

    import android.content.Context;

    import android.os.Environment;

    import android.os.Looper;

    import android.text.TextUtils;

    import android.util.Log;

    import android.widget.Toast;

    import com.emh.pdavoicecall4.constant.Constants;

    import java.io.ByteArrayInputStream;

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.PrintWriter;

    import java.io.StringWriter;

    import java.io.Writer;

    import java.text.SimpleDateFormat;

    import java.util.ArrayList;

    import java.util.Date;

    import java.util.List;

    import java.util.Locale;

    import androidx.annotation.NonNull;

    public class MyCrashHandler implements Thread.UncaughtExceptionHandler {

    private Context context;

    private static final String APP_NAME = Constants.APP_PACKAGE_NAME;

    private String logFilePath = Environment.getExternalStorageDirectory().getPath()

    + File.separator + APP_NAME + File.separator + "Log" + File.separator + "crashlog";

    public MyCrashHandler(Context context) {

    this.context = context;

    }

    @Override

    public void uncaughtException(@NonNull Thread thread, @NonNull final Throwable ex) {

    Log.e("程序出现异常", "Thread = " + thread.getName() + "\nThrowable = " + ex.getMessage());

    String stackTraceInfo = getStackTraceInfo(ex);

    Log.e("stackTraceInfo", stackTraceInfo);

    saveThrowableMessage(stackTraceInfo);

    new Thread() {

    public void run() {

    Looper.prepare();

    Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();

    Looper.loop();

    };

    }.start();

    }

    private String getStackTraceInfo(final Throwable t) {

    PrintWriter pw = null;

    Writer writer = new StringWriter();

    try {

    pw = new PrintWriter(writer);

    t.printStackTrace(pw);

    } catch (Exception e) {

    return "";

    } finally {

    if (pw != null) {

    pw.close();

    }

    }

    return writer.toString();

    }

    private void saveThrowableMessage(String errorMessage) {

    if (TextUtils.isEmpty(errorMessage)) {

    return;

    }

    File file = new File(logFilePath);

    if (!file.exists()) {

    boolean mkdirs = file.mkdirs();

    if (mkdirs) {

    writeStringToFile(errorMessage, file);

    }

    } else {

    writeStringToFile(errorMessage, file);

    }

    }

    private void writeStringToFile(final String errorMessage, final File file) {

    FileOutputStream fos = null;

    try {

    String content = errorMessage + "[" + Utils.getCurrentDateTime() + "]\r\n";

    ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes("UTF-8"));

    File crashLog = createCrashLogFile(file);

    fos = new FileOutputStream(crashLog, true);

    int len = 0;

    byte[] bytes = new byte[1024];

    while ((len = bais.read(bytes)) != -1) {

    fos.write(bytes, 0, len);

    }

    fos.flush();

    Log.e("程序出现异常", "写入本地文件成功:" + file.getAbsolutePath());

    } catch (Exception e) {

    e.printStackTrace();

    } finally {

    if (fos != null) {

    try {

    fos.close();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    }

    private List getAllCrashFiles() {

    File dir = new File(logFilePath);

    File[] files = dir.listFiles();

    List fileNames = new ArrayList<>();

    for (int i = 0; i < files.length; i++) {

    if (files[i].isFile()) {

    fileNames.add(files[i].getName());

    }

    }

    return fileNames;

    }

    private File createCrashLogFile(File file) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);

    String currentDate = sdf.format(new Date());

    File crashLog = new File(file, currentDate + ".txt");

    if (!crashLog.exists()) {

    crashLog.createNewFile();

    List crashLogNames = getAllCrashFiles();

    if (crashLogNames.size() > 10) {

    long currentTimeMilSeconds = new Date().getTime();

    String earliestDate = sdf.format(new Date(currentTimeMilSeconds - 24 * 60 * 60 * 10 * 1000));

    deleteFile(earliestDate + ".txt");

    }

    }

    return crashLog;

    }

    private void deleteFile(String fileName) {

    File file = new File(logFilePath + File.separator + fileName);

    if (file.exists()) {

    file.delete();

    }

    }

    }

    2. 创建类继承Application,初始化MyCrashHandler

    import android.app.Application;

    public class MyApp extends Application {

    @Override

    public void onCreate() {

    // TODO Auto-generated method stub

    super.onCreate();

    MyCrashHandler handler = new MyCrashHandler(getApplicationContext());

    Thread.setDefaultUncaughtExceptionHandler(handler);

    }

    }

    3. 测试

    import android.app.Activity;

    import android.os.Bundle;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    public class MainActivity extends Activity {

    private Button test_crash_btn;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    test_crash_btn = (Button) findViewById(R.id.test_crash_btn);

    test_crash_btn.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    testThreadException();

    }

    });

    }

    private void testUIThreadException() {

    String string = null;

    char[] chars = string.toCharArray();

    }

    private void testThreadException() {

    Thread thread = new Thread(new Runnable() {

    @Override

    public void run() {

    int i = 0;

    int s = 10 / i;

    }

    });

    thread.start();

    }

    }

    展开全文
  • /** * 捕获android程序崩溃日志 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序. * * @author PMTOAM * */ @SuppressLint("SimpleDateFormat") public class CrashHandler implements ...

    主要类:

    package com.example.callstatus;

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.PrintWriter;

    import java.io.StringWriter;

    import java.lang.Thread.UncaughtExceptionHandler;

    import java.lang.reflect.Field;

    import java.net.UnknownHostException;

    import java.text.DateFormat;

    import java.text.SimpleDateFormat;

    import java.util.Date;

    import java.util.HashMap;

    import java.util.Map;

    import android.annotation.SuppressLint;

    import android.content.Context;

    import android.content.pm.PackageInfo;

    import android.content.pm.PackageManager;

    import android.content.pm.PackageManager.NameNotFoundException;

    import android.os.Build;

    import android.os.Environment;

    import android.os.Looper;

    import android.telephony.TelephonyManager;

    import android.text.TextUtils;

    import android.util.Log;

    import android.widget.Toast;

    /**

    * 捕获android程序崩溃日志

    * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序.

    *

    * @author PMTOAM

    *

    */

    @SuppressLint("SimpleDateFormat")

    public class CrashHandler implements UncaughtExceptionHandler

    {

    public static final String TAG = CrashHandler.class.getCanonicalName();

    // 系统默认的UncaughtException处理类

    private Thread.UncaughtExceptionHandler mDefaultHandler;

    // CrashHandler实例

    private static CrashHandler INSTANCE = new CrashHandler();

    // 程序的Context对象

    private Context mContext;

    // 用来存储设备信息和异常信息

    private Map infos = new HashMap();

    // 用于格式化日期,作为日志文件名的一部分

    private DateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");

    /**

    * 保证只有一个实例

    */

    private CrashHandler()

    {

    }

    /**

    * 获取实例 ,单例模式

    */

    public static CrashHandler getInstance()

    {

    return INSTANCE;

    }

    /**

    * 初始化

    *

    * @param context

    */

    public void init(Context context)

    {

    mContext = context;

    // 获取系统默认的UncaughtException处理器

    mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    // 设置该CrashHandler为程序的默认处理器

    Thread.setDefaultUncaughtExceptionHandler(this);

    }

    /**

    * 当UncaughtException发生时会转入该函数来处理

    */

    @Override

    public void uncaughtException(Thread thread, Throwable ex)

    {

    if (!handleException(ex) && mDefaultHandler != null)

    {

    // 如果用户没有处理则让系统默认的异常处理器来处理

    mDefaultHandler.uncaughtException(thread, ex);

    }

    else

    {

    try

    {

    Thread.sleep(3000);

    }

    catch (InterruptedException e)

    {

    Log.e(TAG, "error : ", e);

    }

    // 退出程序

    android.os.Process.killProcess(android.os.Process.myPid());

    System.exit(1);

    }

    }

    /**

    * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.

    *

    * @param ex

    * @return true:如果处理了该异常信息;否则返回false.

    */

    private boolean handleException(Throwable ex)

    {

    if (ex == null)

    {

    return false;

    }

    // 使用Toast来显示异常信息

    new Thread()

    {

    @Override

    public void run()

    {

    Looper.prepare();

    Toast.makeText(mContext, "很抱歉,程序出现异常。", Toast.LENGTH_LONG)

    .show();

    Looper.loop();

    }

    }.start();

    // 收集设备参数信息

    collectDeviceInfo(mContext);

    // 保存日志文件

    String str = saveCrashInfo2File(ex);

    Log.e(TAG, str);

    return false;

    }

    /**

    * 收集设备参数信息

    *

    * @param ctx

    */

    public void collectDeviceInfo(Context ctx)

    {

    try

    {

    PackageManager pm = ctx.getPackageManager();

    PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),

    PackageManager.GET_ACTIVITIES);

    if (pi != null)

    {

    String versionName = pi.versionName == null ? "null"

    : pi.versionName;

    String versionCode = pi.versionCode + "";

    infos.put("versionName", versionName);

    infos.put("versionCode", versionCode);

    }

    }

    catch (NameNotFoundException e)

    {

    Log.e(TAG, "an error occured when collect package info", e);

    }

    Field[] fields = Build.class.getDeclaredFields();

    for (Field field : fields)

    {

    try

    {

    field.setAccessible(true);

    infos.put(field.getName(), field.get(null).toString());

    Log.d(TAG, field.getName() + " : " + field.get(null));

    }

    catch (Exception e)

    {

    Log.e(TAG, "an error occured when collect crash info", e);

    }

    }

    }

    /**

    * 保存错误信息到文件中

    *

    * @param ex

    * @return 返回文件名称,便于将文件传送到服务器

    */

    private String saveCrashInfo2File(Throwable ex)

    {

    StringBuffer sb = new StringBuffer();

    for (Map.Entry entry : infos.entrySet())

    {

    String key = entry.getKey();

    String value = entry.getValue();

    sb.append("[" + key + ", " + value + "]\n");

    }

    sb.append("\n" + getStackTraceString(ex));

    try

    {

    String time = formatter.format(new Date());

    TelephonyManager mTelephonyMgr = (TelephonyManager) mContext

    .getSystemService(Context.TELEPHONY_SERVICE);

    String imei = mTelephonyMgr.getDeviceId();

    if (TextUtils.isEmpty(imei))

    {

    imei = "unknownimei";

    }

    String fileName = "CRS_" + time + "_" + imei + ".txt";

    File sdDir = null;

    if (Environment.getExternalStorageState().equals(

    android.os.Environment.MEDIA_MOUNTED))

    sdDir = Environment.getExternalStorageDirectory();

    File cacheDir = new File(sdDir + File.separator + "dPhoneLog");

    if (!cacheDir.exists())

    cacheDir.mkdir();

    File filePath = new File(cacheDir + File.separator + fileName);

    FileOutputStream fos = new FileOutputStream(filePath);

    fos.write(sb.toString().getBytes());

    fos.close();

    return fileName;

    }

    catch (Exception e)

    {

    Log.e(TAG, "an error occured while writing file...", e);

    }

    return null;

    }

    /**

    * 获取捕捉到的异常的字符串

    */

    public static String getStackTraceString(Throwable tr)

    {

    if (tr == null)

    {

    return "";

    }

    Throwable t = tr;

    while (t != null)

    {

    if (t instanceof UnknownHostException)

    {

    return "";

    }

    t = t.getCause();

    }

    StringWriter sw = new StringWriter();

    PrintWriter pw = new PrintWriter(sw);

    tr.printStackTrace(pw);

    return sw.toString();

    }

    }

    使用方法:

    package com.example.callstatus;

    import android.app.Application;

    public class MyApplication extends Application

    {

    @Override

    public void onCreate()

    {

    super.onCreate();

    CrashHandler crashHandler = CrashHandler.getInstance();

    crashHandler.init(getApplicationContext());

    }

    }

    所需权限:

    原文:http://blog.csdn.net/wangyuexing_blog/article/details/39009069

    展开全文
  • 捕获android程序崩溃日志

    千次阅读 2014-09-02 17:29:57
    * 捕获android程序崩溃日志 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序. * * @author PMTOAM * */ @SuppressLint("SimpleDateFormat") public class CrashHandler ...

    主要类:

    package com.example.callstatus;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.lang.Thread.UncaughtExceptionHandler;
    import java.lang.reflect.Field;
    import java.net.UnknownHostException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.os.Build;
    import android.os.Environment;
    import android.os.Looper;
    import android.telephony.TelephonyManager;
    import android.text.TextUtils;
    import android.util.Log;
    import android.widget.Toast;
    
    /**
     * 捕获android程序崩溃日志<br>
     * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序.
     * 
     * @author PMTOAM
     * 
     */
    @SuppressLint("SimpleDateFormat")
    public class CrashHandler implements UncaughtExceptionHandler
    {
    
    	public static final String TAG = CrashHandler.class.getCanonicalName();
    
    	// 系统默认的UncaughtException处理类
    	private Thread.UncaughtExceptionHandler mDefaultHandler;
    	// CrashHandler实例
    	private static CrashHandler INSTANCE = new CrashHandler();
    	// 程序的Context对象
    	private Context mContext;
    	// 用来存储设备信息和异常信息
    	private Map<String, String> infos = new HashMap<String, String>();
    
    	// 用于格式化日期,作为日志文件名的一部分
    	private DateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
    
    	/**
    	 * 保证只有一个实例
    	 */
    	private CrashHandler()
    	{
    	}
    
    	/**
    	 * 获取实例 ,单例模式
    	 */
    	public static CrashHandler getInstance()
    	{
    		return INSTANCE;
    	}
    
    	/**
    	 * 初始化
    	 * 
    	 * @param context
    	 */
    	public void init(Context context)
    	{
    		mContext = context;
    		// 获取系统默认的UncaughtException处理器
    		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    		// 设置该CrashHandler为程序的默认处理器
    		Thread.setDefaultUncaughtExceptionHandler(this);
    	}
    
    	/**
    	 * 当UncaughtException发生时会转入该函数来处理
    	 */
    	@Override
    	public void uncaughtException(Thread thread, Throwable ex)
    	{
    		if (!handleException(ex) && mDefaultHandler != null)
    		{
    			// 如果用户没有处理则让系统默认的异常处理器来处理
    			mDefaultHandler.uncaughtException(thread, ex);
    		}
    		else
    		{
    			try
    			{
    				Thread.sleep(3000);
    			}
    			catch (InterruptedException e)
    			{
    				Log.e(TAG, "error : ", e);
    			}
    
    			// 退出程序
    			android.os.Process.killProcess(android.os.Process.myPid());
    			System.exit(1);
    		}
    	}
    
    	/**
    	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
    	 * 
    	 * @param ex
    	 * @return true:如果处理了该异常信息;否则返回false.
    	 */
    	private boolean handleException(Throwable ex)
    	{
    		if (ex == null)
    		{
    			return false;
    		}
    
    		// 使用Toast来显示异常信息
    		new Thread()
    		{
    			@Override
    			public void run()
    			{
    				Looper.prepare();
    				Toast.makeText(mContext, "很抱歉,程序出现异常。", Toast.LENGTH_LONG)
    						.show();
    				Looper.loop();
    			}
    		}.start();
    
    		// 收集设备参数信息
    		collectDeviceInfo(mContext);
    
    		// 保存日志文件
    		String str = saveCrashInfo2File(ex);
    		Log.e(TAG, str);
    
    		return false;
    	}
    
    	/**
    	 * 收集设备参数信息
    	 * 
    	 * @param ctx
    	 */
    	public void collectDeviceInfo(Context ctx)
    	{
    		try
    		{
    			PackageManager pm = ctx.getPackageManager();
    			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
    					PackageManager.GET_ACTIVITIES);
    			if (pi != null)
    			{
    				String versionName = pi.versionName == null ? "null"
    						: pi.versionName;
    				String versionCode = pi.versionCode + "";
    				infos.put("versionName", versionName);
    				infos.put("versionCode", versionCode);
    			}
    
    		}
    		catch (NameNotFoundException e)
    		{
    			Log.e(TAG, "an error occured when collect package info", e);
    		}
    		Field[] fields = Build.class.getDeclaredFields();
    		for (Field field : fields)
    		{
    			try
    			{
    				field.setAccessible(true);
    				infos.put(field.getName(), field.get(null).toString());
    				Log.d(TAG, field.getName() + " : " + field.get(null));
    			}
    			catch (Exception e)
    			{
    				Log.e(TAG, "an error occured when collect crash info", e);
    			}
    		}
    	}
    
    	/**
    	 * 保存错误信息到文件中
    	 * 
    	 * @param ex
    	 * @return 返回文件名称,便于将文件传送到服务器
    	 */
    	private String saveCrashInfo2File(Throwable ex)
    	{
    
    		StringBuffer sb = new StringBuffer();
    		for (Map.Entry<String, String> entry : infos.entrySet())
    		{
    			String key = entry.getKey();
    			String value = entry.getValue();
    			sb.append("[" + key + ", " + value + "]\n");
    		}
    
    		sb.append("\n" + getStackTraceString(ex));
    
    		try
    		{
    			String time = formatter.format(new Date());
    
    			TelephonyManager mTelephonyMgr = (TelephonyManager) mContext
    					.getSystemService(Context.TELEPHONY_SERVICE);
    			String imei = mTelephonyMgr.getDeviceId();
    			if (TextUtils.isEmpty(imei))
    			{
    				imei = "unknownimei";
    			}
    
    			String fileName = "CRS_" + time + "_" + imei + ".txt";
    
    			File sdDir = null;
    
    			if (Environment.getExternalStorageState().equals(
    					android.os.Environment.MEDIA_MOUNTED))
    				sdDir = Environment.getExternalStorageDirectory();
    
    			File cacheDir = new File(sdDir + File.separator + "dPhoneLog");
    			if (!cacheDir.exists())
    				cacheDir.mkdir();
    
    			File filePath = new File(cacheDir + File.separator + fileName);
    
    			FileOutputStream fos = new FileOutputStream(filePath);
    			fos.write(sb.toString().getBytes());
    			fos.close();
    
    			return fileName;
    		}
    		catch (Exception e)
    		{
    			Log.e(TAG, "an error occured while writing file...", e);
    		}
    		return null;
    	}
    
    	/**
    	 * 获取捕捉到的异常的字符串
    	 */
    	public static String getStackTraceString(Throwable tr)
    	{
    		if (tr == null)
    		{
    			return "";
    		}
    
    		Throwable t = tr;
    		while (t != null)
    		{
    			if (t instanceof UnknownHostException)
    			{
    				return "";
    			}
    			t = t.getCause();
    		}
    
    		StringWriter sw = new StringWriter();
    		PrintWriter pw = new PrintWriter(sw);
    		tr.printStackTrace(pw);
    		return sw.toString();
    	}
    }
    


    使用方法:


    package com.example.callstatus;
    
    import android.app.Application;
    
    public class MyApplication extends Application
    {
    	@Override
    	public void onCreate()
    	{
    		super.onCreate();
    		
    		CrashHandler crashHandler = CrashHandler.getInstance();
    		crashHandler.init(getApplicationContext());
    	}
    }
    


    所需权限:


    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />


    展开全文
  • android程序崩溃日志

    2015-10-14 11:18:00
    * 捕获android程序崩溃日志 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序. * * @author PMTOAM * */ @SuppressLint("SimpleDateFormat") public class CrashHandler ...

    主要类别:

    package com.example.callstatus;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.lang.Thread.UncaughtExceptionHandler;
    import java.lang.reflect.Field;
    import java.net.UnknownHostException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.os.Build;
    import android.os.Environment;
    import android.os.Looper;
    import android.telephony.TelephonyManager;
    import android.text.TextUtils;
    import android.util.Log;
    import android.widget.Toast;
    
    /**
     * 捕获android程序崩溃日志<br>
     * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序.
     * 
     * @author PMTOAM
     * 
     */
    @SuppressLint("SimpleDateFormat")
    public class CrashHandler implements UncaughtExceptionHandler
    {
    
    	public static final String TAG = CrashHandler.class.getCanonicalName();
    
    	// 系统默认的UncaughtException处理类
    	private Thread.UncaughtExceptionHandler mDefaultHandler;
    	// CrashHandler实例
    	private static CrashHandler INSTANCE = new CrashHandler();
    	// 程序的Context对象
    	private Context mContext;
    	// 用来存储设备信息和异常信息
    	private Map<String, String> infos = new HashMap<String, String>();
    
    	// 用于格式化日期,作为日志文件名称的一部分
    	private DateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
    
    	/**
    	 * 保证仅仅有一个实例
    	 */
    	private CrashHandler()
    	{
    	}
    
    	/**
    	 * 获取实例 ,单例模式
    	 */
    	public static CrashHandler getInstance()
    	{
    		return INSTANCE;
    	}
    
    	/**
    	 * 初始化
    	 * 
    	 * @param context
    	 */
    	public void init(Context context)
    	{
    		mContext = context;
    		// 获取系统默认的UncaughtException处理器
    		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    		// 设置该CrashHandler为程序的默认处理器
    		Thread.setDefaultUncaughtExceptionHandler(this);
    	}
    
    	/**
    	 * 当UncaughtException发生时会转入该函数来处理
    	 */
    	@Override
    	public void uncaughtException(Thread thread, Throwable ex)
    	{
    		if (!handleException(ex) && mDefaultHandler != null)
    		{
    			// 假设用户没有处理则让系统默认的异常处理器来处理
    			mDefaultHandler.uncaughtException(thread, ex);
    		}
    		else
    		{
    			try
    			{
    				Thread.sleep(3000);
    			}
    			catch (InterruptedException e)
    			{
    				Log.e(TAG, "error : ", e);
    			}
    
    			// 退出程序
    			android.os.Process.killProcess(android.os.Process.myPid());
    			System.exit(1);
    		}
    	}
    
    	/**
    	 * 自己定义错误处理,收集错误信息 发送错误报告等操作均在此完毕.
    	 * 
    	 * @param ex
    	 * @return true:假设处理了该异常信息;否则返回false.
    	 */
    	private boolean handleException(Throwable ex)
    	{
    		if (ex == null)
    		{
    			return false;
    		}
    
    		// 使用Toast来显示异常信息
    		new Thread()
    		{
    			@Override
    			public void run()
    			{
    				Looper.prepare();
    				Toast.makeText(mContext, "非常抱歉。程序出现异常。

    ", Toast.LENGTH_LONG) .show(); Looper.loop(); } }.start(); // 收集设备參数信息 collectDeviceInfo(mContext); // 保存日志文件 String str = saveCrashInfo2File(ex); Log.e(TAG, str); return false; } /** * 收集设备參数信息 * * @param ctx */ public void collectDeviceInfo(Context ctx) { try { PackageManager pm = ctx.getPackageManager(); PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { String versionName = pi.versionName == null ?

    "null" : pi.versionName; String versionCode = pi.versionCode + ""; infos.put("versionName", versionName); infos.put("versionCode", versionCode); } } catch (NameNotFoundException e) { Log.e(TAG, "an error occured when collect package info", e); } Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); infos.put(field.getName(), field.get(null).toString()); Log.d(TAG, field.getName() + " : " + field.get(null)); } catch (Exception e) { Log.e(TAG, "an error occured when collect crash info", e); } } } /** * 保存错误信息到文件里 * * @param ex * @return 返回文件名称称,便于将文件传送到server */ private String saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append("[" + key + ", " + value + "]\n"); } sb.append("\n" + getStackTraceString(ex)); try { String time = formatter.format(new Date()); TelephonyManager mTelephonyMgr = (TelephonyManager) mContext .getSystemService(Context.TELEPHONY_SERVICE); String imei = mTelephonyMgr.getDeviceId(); if (TextUtils.isEmpty(imei)) { imei = "unknownimei"; } String fileName = "CRS_" + time + "_" + imei + ".txt"; File sdDir = null; if (Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) sdDir = Environment.getExternalStorageDirectory(); File cacheDir = new File(sdDir + File.separator + "dPhoneLog"); if (!cacheDir.exists()) cacheDir.mkdir(); File filePath = new File(cacheDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(filePath); fos.write(sb.toString().getBytes()); fos.close(); return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } /** * 获取捕捉到的异常的字符串 */ public static String getStackTraceString(Throwable tr) { if (tr == null) { return ""; } Throwable t = tr; while (t != null) { if (t instanceof UnknownHostException) { return ""; } t = t.getCause(); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); tr.printStackTrace(pw); return sw.toString(); } }



    用法:


    package com.example.callstatus;
    
    import android.app.Application;
    
    public class MyApplication extends Application
    {
    	@Override
    	public void onCreate()
    	{
    		super.onCreate();
    		
    		CrashHandler crashHandler = CrashHandler.getInstance();
    		crashHandler.init(getApplicationContext());
    	}
    }
    


    所需权限:


    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />


    版权声明:本文博主原创文章。博客,未经同意不得转载。

    展开全文
  • private boolean writeToSDCard(Throwable ex) { boolean isDealing = false; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { RandomAccessFile rand...
  • Debug监听程序崩溃日志,直接页面展示崩溃日志列表
  • Android收集程序崩溃日志

    万次阅读 2018-08-30 17:21:08
    我们都知道我们的android程序是跑在UI线程中的,而且我们会在程序中创建各种子线程。为了统一,如果我们给每个线程都通过 setUncaughtExceptionHandler() 这个方法来设置 UncaughtExceptionHandler 的话,未免太不...
  • Android 收集程序崩溃日志,保存本地。 public class CrashHandler implements Thread.UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; String crashHead; // 系统默.....
  • Android 应用程序崩溃日志到文件。 这是将崩溃日志写入 android 应用程序中的文件的代码。 现有的 Android 日志崩溃日志仅在开发人员模式下。 当 crashlog 将 libcrashlog.so 动态加载到应用程序中时,它会在应用...
  • MNCrashMonitor 监听程序崩溃日志,直接页面展示崩溃日志列表,调试方便,测试人员可以随时给程序猿查看日志详情,可以动态添加日志内容,手机直接查看日志内容可以分享,复制,生成长截图,高亮显示。 截图 如何添加...
  • 程序崩溃是应用迭代中不可避免的问题,即使有着5年或者10年经验的程序猿也无法完全保证自己的代码没有任何的bug导致崩溃,现在有一些第三方平台可以帮助我们搜集应用程序的崩溃,比如友盟,详情如下图 虽然能够...
  • 在开发程序的过程中,由于不同的手机的系统版本不同,或者是修改过的系统,在开发的过程中没有那么多的测试手机,只好把错误的信息收集起来使用啦,在网上看了人家的日志, ... 里面介绍的很好,就把人家的代码扣下来...
  • android 程序崩溃crash日志的捕捉 之前在项目开发过程中,一直会遇到程序崩溃了,但是测试組的哥哥们又没及时的导出日志.... 后来在诳群的时候听别人说起,腾讯有那么一个叫bugly的东西 将其作为第三方jar文件引入...
  • 崩溃日志的捕获有很多种方式,最直接的就是接入三方的捕获,但是由于某些原因或者说某些原因导致不能准确的定位到崩溃的位置,也为了使应用程序测试时更好的定位崩溃位置(测试机多的时候不可能每个都去打LOG和断点) ...
  • 安防
  • 今天开发时,写的一个demo,运行后程序崩溃了,但是Android Studio上没显示崩溃日志。然后运行了好几次,还是没显示,但是另一个Android Studio(其他程序在跑)却显示日志。我才发现之前的Android Studio连日志都...
  • 捕获android程序崩溃异常日志

    千次阅读 2016-12-27 17:50:46
    //android.os.Process.killProcess(android.os.Process.myPid()); System. exit ( 0 ); } }); buildAlert.setTitle(R.string. app_crash_tips ); buildAlert.setCanceledOnTouchOutside( false ); ...
  • 一个demo,收集Android程序崩溃日志,保存到SD卡中
  • 当我使用Android Studio时,应用程序崩溃时清空Logcat看不到崩溃日志。通过设置logcatfilter : 1、单击logcat右侧的编辑filterconfiguration 2、设置您的应用程序ID,然后单击确定 此时就可以看到崩溃日志了! ...
  • Android 应用程序崩溃,是最让人头疼的,崩溃日志的获取有各种方法,下面给出最简单的一种 找到SDK目录D:\MySDK\tools\lib\monitor-x86_64/monitor.exe,双击它! 就能看到应用程序所有日志,还能保存txt文本 ...
  • 在编译Android底层的jni程序时,有两种编译方式:ndk和cmake,现在针对两种不同的编译方式来定位出崩溃的具体行号 ndk: 1、找到你的项目工程里的jni生成的目录,比如说目录为:obj/armeabi/objs/ 2、拿到崩溃的地址...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 13,906
精华内容 5,562
关键字:

安卓程序崩溃日志