栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

/ExternalStorage/MyPersonalAppFolder/logs/logcat_XXX.txt

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

public class MyPersonalApp extends Application {        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        }    }        public boolean isExternalStorageWritable() {        String state = Environment.getExternalStorageState();        if ( Environment.MEDIA_MOUNTED.equals( state ) ) { return true;        }        return false;    }        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");


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号