gpt4 book ai didi

android - logcat 停止写入设备上的文件

转载 作者:行者123 更新时间:2023-12-05 00:06:42 28 4
gpt4 key购买 nike

对于 Android 应用程序,我将日志保存在设备本身上,以便在出现问题时我们可以找出问题所在。此设备在无互联网环境中运行,因此无法远程写入日志。

下面的代码首先清除缓冲区,然后将记录的内容连续写入“logFile”。

    try {
Process process = Runtime.getRuntime().exec("logcat -c"); // -c clear buffer.
process = Runtime.getRuntime().exec("logcat -f " + logFile + " -r 5120 -n 30"); // -r amount of bits to write, -n amount of logs to rotate
} catch ( IOException e ) {
e.printStackTrace();
}

这段代码工作正常,除了在一段时间、几小时或几天后它随机停止保存日志。

这可能是什么原因造成的,我该如何解决?

最佳答案

我认为您应该先检查权限。您可能正在棉花糖及更高版本中测试应用程序。请尝试以下代码,让我知道它是否适合您:

    public class MyProjectApp 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() + "/MyProjectAppFolder" );
File logDirectory = new File( appDirectory + "/log" );
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" />

来源来源:http://www.journal.deviantdev.com/android-log-logcat-to-file-while-runtime/

关于android - logcat 停止写入设备上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50942506/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com