4

在 Android 应用程序中强制关闭时如何在运行时获取日志。我想获取日志并邮寄。

4

3 回答 3

3

这里有一些代码来收集应用程序内部的日志:

    private int MAX_LOG_MESSAGE_LENGTH = 100000;
    private String[] mFilterSpecs;
    private String mFormat;
    private String mBuffer;

private class CollectLogTask extends AsyncTask<ArrayList<String>, Void, StringBuilder> {
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected StringBuilder doInBackground(ArrayList<String>... params) {
        final StringBuilder log = new StringBuilder();
        try {
            ArrayList<String> commandLine = new ArrayList<String>();
            commandLine.add("logcat");//$NON-NLS-1$
            commandLine.add("-d");//$NON-NLS-1$
            ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;
            if (null != arguments) {
                commandLine.addAll(arguments);
            }

            Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                log.append(line);
                log.append(LINE_SEPARATOR);
            }
        } catch (IOException e) {
            Log.e(TAG, "CollectLogTask.doInBackground failed", e);//$NON-NLS-1$
        }

        return log;
    }

    @Override
    protected void onPostExecute(final StringBuilder log) {
        if (null != log) {
            // truncate if necessary
            int keepOffset = Math.max(log.length() - MAX_LOG_MESSAGE_LENGTH, 0);
            if (keepOffset > 0) {
                log.delete(0, keepOffset);
            }

            if (mAdditonalInfo != null) {
                log.insert(0, LINE_SEPARATOR);
                log.insert(0, mAdditonalInfo);
            }
                          Log.d("printLog",log.toString());

        }
    }
}

现在像这样调用这个异步类。

    ArrayList<String> list = new ArrayList<String>();

    if (mFormat != null) {
        list.add("-v");
        list.add(mFormat);
    }

    if (mBuffer != null) {
        list.add("-b");
        list.add(mBuffer);
    }

    if (mFilterSpecs != null) {
        for (String filterSpec : mFilterSpecs) {
            list.add(filterSpec);
        }
    }

    new CollectLogTask().execute(list);
于 2012-12-13T14:05:17.967 回答
2

使用ACRA或相关库来捕获生产应用程序的崩溃并处理这些报告。默认情况下,ACRA 会将材料记录到 Google Docs 电子表格中,但您可以将其替换为其他内容。

于 2012-12-13T14:10:23.460 回答
1

adb logcat当设备在 USB 调试中连接时

或者

从 gplay安装aLogCat

于 2012-12-13T13:38:44.363 回答