将Logcat保存到Android设备中的文本文件

我在android设备上运行应用程序时发现一些崩溃,但未在模拟器中显示。因此,我需要将Logcat保存在设备内存或SD卡中的文本文件中。您能否建议我一个好的方法来做到这一点?

回答:

在应用程序的开头使用Application类。这样可以进行正确的文件和日志处理。

下面的代码在以下位置创建一个日志文件:

/ExternalStorage/MyPersonalAppFolder/logs/logcat_XXX.txt

XXX是当前时间(以毫秒为单位)。每次您运行应用程序时,都会创建一个新的logcat_XXX.txt文件。

public class MyPersonalApp extends Application {

/**

* Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

*/

public void onCreate() {

super.onCreate();

if ( isExternalStorageWritable() ) {

File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" );

File logDirectory = new File( appDirectory + "/logs" );

File logFile = new File( logDirectory, "logcat_" + System.currentTimeMillis() + ".txt" );

// create app folder

if ( !appDirectory.exists() ) {

appDirectory.mkdir();

}

// create log folder

if ( !logDirectory.exists() ) {

logDirectory.mkdir();

}

// clear the previous logcat and then write the new one to the file

try {

Process process = Runtime.getRuntime().exec("logcat -c");

process = Runtime.getRuntime().exec("logcat -f " + logFile);

} catch ( IOException e ) {

e.printStackTrace();

}

} else if ( isExternalStorageReadable() ) {

// only readable

} else {

// not accessible

}

}

/* Checks if external storage is available for read and write */

public boolean isExternalStorageWritable() {

String state = Environment.getExternalStorageState();

if ( Environment.MEDIA_MOUNTED.equals( state ) ) {

return true;

}

return false;

}

/* Checks if external storage is available to at least read */

public boolean isExternalStorageReadable() {

String state = Environment.getExternalStorageState();

if ( Environment.MEDIA_MOUNTED.equals( state ) ||

Environment.MEDIA_MOUNTED_READ_ONLY.equals( state ) ) {

return true;

}

return false;

}

}

您需要在.manifest文件中使用正确的权限和应用程序类的名称:

<uses-permission android:name="android.permission.READ_LOGS" />

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

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application

android:name=".MyPersonalApp"

... >

如果您只想保存某些特定活动的日志。

更换:

process = Runtime.getRuntime().exec("logcat -f " + logFile);

与:

process = Runtime.getRuntime().exec( "logcat -f " + logFile + " *:S MyActivity:D MyActivity2:D");

以上是 将Logcat保存到Android设备中的文本文件 的全部内容, 来源链接: utcz.com/qa/419293.html

回到顶部