需要处理未捕获的异常并发送日志文件

Per*_*man 107 android exception-handling logcat

更新:请参阅下面的"已接受"解决方案

当我的应用创建未处理的异常,而不是简单地终止时,我想首先让用户有机会发送日志文件.我意识到在获得随机异常后做更多的工作是有风险的,但是,嘿,最糟糕的是应用程序完成崩溃并且日志文件没有被发送.结果比我想象的更棘手:)

什么有效:(1)捕获未捕获的异常,(2)提取日志信息并写入文件.

什么不起作用:(3)开始发送电子邮件的活动.最终,我还有另一项活动要求用户的许可.如果我让电子邮件活动正常工作,我不会对另一方感到麻烦.

问题的关键是我的Application类中捕获了未处理的异常.由于这不是一个Activity,因此如何使用Intent.ACTION_SEND启动活动并不明显.也就是说,通常在启动一个活动时,调用startActivity并使用onActivityResult恢复.Activity支持这些方法,但Application不支持.

有关如何做到这一点的任何建议?

以下是一些代码剪辑作为入门指南:

public class MyApplication extends Application
{
  defaultUncaughtHandler = Thread.getDefaultUncaughtExceptionHandler();
  public void onCreate ()
  {
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
      @Override
      public void uncaughtException (Thread thread, Throwable e)
      {
        handleUncaughtException (thread, e);
      }
    });
  }

  private void handleUncaughtException (Thread thread, Throwable e)
  {
    String fullFileName = extractLogToFile(); // code not shown

    // The following shows what I'd like, though it won't work like this.
    Intent intent = new Intent (Intent.ACTION_SEND);
    intent.setType ("plain/text");
    intent.putExtra (Intent.EXTRA_EMAIL, new String[] {"me@mydomain.com"});
    intent.putExtra (Intent.EXTRA_SUBJECT, "log file");
    intent.putExtra (Intent.EXTRA_STREAM, Uri.parse ("file://" + fullFileName));
    startActivityForResult (intent, ACTIVITY_REQUEST_SEND_LOG);
  }

  public void onActivityResult (int requestCode, int resultCode, Intent data)
  {
    if (requestCode == ACTIVITY_REQUEST_SEND_LOG)
      System.exit(1);
  }
}
Run Code Online (Sandbox Code Playgroud)

Per*_*man 234

这是完整的解决方案(几乎:我省略了UI布局和按钮处理) - 来自大量实验和其他与其他问题相关的帖子.

您需要做很多事情:

  1. 在Application子类中处理uncaughtException.
  2. 捕获异常后,启动一个新活动以要求用户发送日志.
  3. 从logcat的文件中提取日志信息并写入您自己的文件.
  4. 启动电子邮件应用,将您的文件作为附件提供.
  5. 清单:过滤您的活动,以便您的异常处理程序识别.
  6. (可选)设置Proguard以去除Log.d()和Log.v().

现在,这里有详细信息:

(1&2)处理uncaughtException,开始发送日志活动:

public class MyApplication extends Application
{
  public void onCreate ()
  {
    // Setup handler for uncaught exceptions.
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
      @Override
      public void uncaughtException (Thread thread, Throwable e)
      {
        handleUncaughtException (thread, e);
      }
    });
  }

  public void handleUncaughtException (Thread thread, Throwable e)
  {
    e.printStackTrace(); // not all Android versions will print the stack trace automatically

    Intent intent = new Intent ();
    intent.setAction ("com.mydomain.SEND_LOG"); // see step 5.
    intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
    startActivity (intent);

    System.exit(1); // kill off the crashed app
  }
}
Run Code Online (Sandbox Code Playgroud)

(3)提取日志(我把它作为我的SendLog活动):

private String extractLogToFile()
{
  PackageManager manager = this.getPackageManager();
  PackageInfo info = null;
  try {
    info = manager.getPackageInfo (this.getPackageName(), 0);
  } catch (NameNotFoundException e2) {
  }
  String model = Build.MODEL;
  if (!model.startsWith(Build.MANUFACTURER))
    model = Build.MANUFACTURER + " " + model;

  // Make file name - file must be saved to external storage or it wont be readable by
  // the email app.
  String path = Environment.getExternalStorageDirectory() + "/" + "MyApp/";
  String fullName = path + <some name>;

  // Extract to file.
  File file = new File (fullName);
  InputStreamReader reader = null;
  FileWriter writer = null;
  try
  {
    // For Android 4.0 and earlier, you will get all app's log output, so filter it to
    // mostly limit it to your app's output.  In later versions, the filtering isn't needed.
    String cmd = (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) ?
                  "logcat -d -v time MyApp:v dalvikvm:v System.err:v *:s" :
                  "logcat -d -v time";

    // get input stream
    Process process = Runtime.getRuntime().exec(cmd);
    reader = new InputStreamReader (process.getInputStream());

    // write output stream
    writer = new FileWriter (file);
    writer.write ("Android version: " +  Build.VERSION.SDK_INT + "\n");
    writer.write ("Device: " + model + "\n");
    writer.write ("App version: " + (info == null ? "(null)" : info.versionCode) + "\n");

    char[] buffer = new char[10000];
    do 
    {
      int n = reader.read (buffer, 0, buffer.length);
      if (n == -1)
        break;
      writer.write (buffer, 0, n);
    } while (true);

    reader.close();
    writer.close();
  }
  catch (IOException e)
  {
    if (writer != null)
      try {
        writer.close();
      } catch (IOException e1) {
      }
    if (reader != null)
      try {
        reader.close();
      } catch (IOException e1) {
      }

    // You might want to write a failure message to the log here.
    return null;
  }

  return fullName;
}
Run Code Online (Sandbox Code Playgroud)

(4)启动电子邮件应用程序(也在我的SendLog活动中):

private void sendLogFile ()
{
  String fullName = extractLogToFile();
  if (fullName == null)
    return;

  Intent intent = new Intent (Intent.ACTION_SEND);
  intent.setType ("plain/text");
  intent.putExtra (Intent.EXTRA_EMAIL, new String[] {"log@mydomain.com"});
  intent.putExtra (Intent.EXTRA_SUBJECT, "MyApp log file");
  intent.putExtra (Intent.EXTRA_STREAM, Uri.parse ("file://" + fullName));
  intent.putExtra (Intent.EXTRA_TEXT, "Log file attached."); // do this so some email clients don't complain about empty body.
  startActivity (intent);
}
Run Code Online (Sandbox Code Playgroud)

(3&4)这就是SendLog的样子(你必须添加UI):

public class SendLog extends Activity implements OnClickListener
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    requestWindowFeature (Window.FEATURE_NO_TITLE); // make a dialog without a titlebar
    setFinishOnTouchOutside (false); // prevent users from dismissing the dialog by tapping outside
    setContentView (R.layout.send_log);
  }

  @Override
  public void onClick (View v) 
  {
    // respond to button clicks in your UI
  }

  private void sendLogFile ()
  {
    // method as shown above
  }

  private String extractLogToFile()
  {
    // method as shown above
  }
}
Run Code Online (Sandbox Code Playgroud)

(5)清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <!-- needed for Android 4.0.x and eariler -->
    <uses-permission android:name="android.permission.READ_LOGS" /> 

    <application ... >
        <activity
            android:name="com.mydomain.SendLog"
            android:theme="@android:style/Theme.Dialog"
            android:textAppearance="@android:style/TextAppearance.Large"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
              <action android:name="com.mydomain.SEND_LOG" />
              <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
     </application>
</manifest>
Run Code Online (Sandbox Code Playgroud)

(6)设置Proguard:

在project.properties中,更改配置行.您必须指定"optimize"或Proguard 不会删除Log.v()和Log.d()调用.

proguard.config=${sdk.dir}/tools/proguard/proguard-android-optimize.txt:proguard-project.txt
Run Code Online (Sandbox Code Playgroud)

在proguard-project.txt中,添加以下内容.这告诉Proguard假设Log.v和Log.d没有副作用(即使他们写入日志时也这样做)因此可以在优化期间删除:

-assumenosideeffects class android.util.Log {
    public static int v(...);
    public static int d(...);
}
Run Code Online (Sandbox Code Playgroud)

而已!如果您对此有任何改进建议,请告诉我,我可能会更新此信息.

  • 只需注意:永远不要调用System.exit.你将打破未捕获的异常处理程序链.把它转发到下一个.你已经从getDefaultUncaughtExceptionHandler获得了"defaultUncaughtHandler",只需在完成后将调用传递给它. (10认同)
  • @PeriHartman肯定:只有一个默认处理程序.在调用setDefaultUncaughtExceptionHandler()之前,必须调用getDefaultUncaughtExceptionHandler()并保留该引用.所以,假设你有bugsense,crashlytics和你的处理程序是最后安装的,系统将只调用你的.你的任务是通过getDefaultUncaughtExceptionHandler()调用你收到的引用,并将线程和throwable传递给链中的下一个.如果您只是System.exit(),则不会调用其他人. (8认同)
  • 您还需要在清单中使用Application标记中的属性注册Application的实现,例如:<application android:name ="com.mydomain.MyApplication"other attrs ... /> (4认同)
  • @gilm,你能举例说明如何"将它转发到下一个"以及处理程序链中可能发生的其他事情吗?已经有一段时间了,但我测试了很多场景,并且调用System.exit()似乎是最好的解决方案.毕竟,应用程序崩溃了,它需要终止. (2认同)

小智 8

今天有许多碰撞重新设计工具可以轻松完成.

  1. crashlytics - 崩溃报告工具,免费但为您提供基本报告优点:免费

  2. Gryphonet - 一种更先进的报告工具,需要一些费用.优点:轻松恢复崩溃,ANR,缓慢......

如果你是私人开发者我会建议Crashlytics,但如果它是一个大组织,我会去Gryphonet.

祝好运!


Mar*_*cny 5

尝试使用ACRA - 它处理堆栈跟踪以及大量其他有用的调试信息到您的后端或您设置的Google Docs文档.

https://github.com/ACRA/acra


小智 5

当UI线程引发未捕获的异常时,@ PeriHartman的答案很好用。我对非UI线程抛出未捕获的异常时进行了一些改进。

public boolean isUIThread(){
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

public void handleUncaughtException(Thread thread, Throwable e) {
    e.printStackTrace(); // not all Android versions will print the stack trace automatically

    if(isUIThread()) {
        invokeLogActivity();
    }else{  //handle non UI thread throw uncaught exception

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                invokeLogActivity();
            }
        });
    }
}

private void invokeLogActivity(){
    Intent intent = new Intent ();
    intent.setAction ("com.mydomain.SEND_LOG"); // see step 5.
    intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
    startActivity (intent);

    System.exit(1); // kill off the crashed app
}
Run Code Online (Sandbox Code Playgroud)