概述
这里介绍两种方法:目前使用 方法一
方法一:
添加权限:
示例代码:
public class MyApp extends Application {
private Process mLogProcess;
@Override
public void onCreate() {
super.onCreate();
try {
int pid = android.os.Process.myPid();
Log.d("MyApp", "PID is " + pid);
Calendar calendar = Calendar.getInstance();
String filename = String.format("/sdcard/MyApp_Log_%04d%02d%02d_%02d%02d%02d.txt",
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND));
mLogProcess = Runtime.getRuntime().exec(String.format("logcat -v time -f %s", filename));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onTerminate() {
super.onTerminate();
if(mLogProcess != null ){
mLogProcess.destroy();
}
}
}
方法二:
添加权限 同上;
示例代码:
package com.way.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Environment;
/**
* log日志统计保存
*
* @author way
*
*/
public class LogcatHelper {
private static LogcatHelper INSTANCE = null;
private static String PATH_LOGCAT;
private LogDumper mLogDumper = null;
private int mPId;
/**
*
* 初始化目录
*
* */
public void init(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
PATH_LOGCAT = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "miniGPS";
} else {// 如果SD卡不存在,就保存到本应用的目录下
PATH_LOGCAT = context.getFilesDir().getAbsolutePath()
+ File.separator + "miniGPS";
}
File file = new File(PATH_LOGCAT);
if (!file.exists()) {
file.mkdirs();
}
}
public static LogcatHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new LogcatHelper(context);
}
return INSTANCE;
}
private LogcatHelper(Context context) {
init(context);
mPId = android.os.Process.myPid();
}
public void start() {
if (mLogDumper == null)
mLogDumper = new LogDumper(String.valueOf(mPId), PATH_LOGCAT);
mLogDumper.start();
}
public void stop() {
if (mLogDumper != null) {
mLogDumper.stopLogs();
mLogDumper = null;
}
}
private class LogDumper extends Thread {
private Process logcatProc;
private BufferedReader mReader = null;
private boolean mRunning = true;
String cmds = null;
private String mPID;
private FileOutputStream out = null;
public LogDumper(String pid, String dir) {
mPID = pid;
try {
out = new FileOutputStream(new File(dir, "GPS-"
+ MyDate.getFileName() + ".log"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
*
* 日志等级:*:v , *:d , *:w , *:e , *:f , *:s
*
* 显示当前mPID程序的 E和W等级的日志.
*
* */
// cmds = "logcat *:e *:w | grep "(" + mPID + ")"";
// cmds = "logcat | grep "(" + mPID + ")"";//打印所有日志信息
// cmds = "logcat -s way";//打印标签过滤信息
cmds = "logcat *:e *:i | grep "(" + mPID + ")"";
}
public void stopLogs() {
mRunning = false;
}
@Override
public void run() {
try {
logcatProc = Runtime.getRuntime().exec(cmds);
mReader = new BufferedReader(new InputStreamReader(
logcatProc.getInputStream()), 1024);
String line = null;
while (mRunning && (line = mReader.readLine()) != null) {
if (!mRunning) {
break;
}
if (line.length() == 0) {
continue;
}
if (out != null && line.contains(mPID)) {
out.write((MyDate.getDateEN() + " " + line + "n")
.getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (logcatProc != null) {
logcatProc.destroy();
logcatProc = null;
}
if (mReader != null) {
try {
mReader.close();
mReader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
}
}
}
时间工具类:
package com.way.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static String getFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new Date(System.currentTimeMillis()));
return date;// 2012年10月03日 23:41:31
}
public static String getDateEN() {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1 = format1.format(new Date(System.currentTimeMillis()));
return date1;// 2012-10-03 23:41:31
}
}
OK,所有事情做完之后,在我们的应用中start一下就OK了,使用完之后,记得调用一下stop:
public class GPSApplication extends Application {
@Override
public void onCreate() {
// TODO Auto-generated method stub
LogcatHelper.getInstance(this).start();
}
}
方法三:
示例代码:
public class CrashHandler implements UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
public static final String TAG = "CatchExcep";
CompRegisterApp application;
public CrashHandler(CompRegisterApp application){
//获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
this.application = application;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if(!handleException(ex) && mDefaultHandler != null){
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
}else{
try{
Thread.sleep(2000);
}catch (InterruptedException e){
Log.e(TAG, "error : ", e);
}
Intent intent = new Intent(application.getApplicationContext(), LaunchActivity.class);
PendingIntent restartIntent = PendingIntent.getActivity(
application.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
//退出程序
AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
application.finishActivity();
}
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(final Throwable ex) {
if (ex == null) {
return false;
}
//使用Toast来显示异常信息
new Thread(){
@Override
public void run() {
Looper.prepare();
Toast.makeText(application.getApplicationContext(), "程序出现异常n"+ex.toString()+"n即将退出.",
Toast.LENGTH_SHORT).show();
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
String strs = sw.toString();
writeFile(strs);
Looper.loop();
}
}.start();
return true;
}
private static void writeFile(String logStr)
{
Date curDate = new Date(System.currentTimeMillis());
// 保存的日期格式
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String pathStr = FileUtilNew.getSDCardPath() + "/HJKJ/log/" + formatter.format(curDate) + ".txt";
File file = new File(pathStr);
if(!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
try
{
FileOutputStream out = new FileOutputStream(pathStr, file.exists());
out.write((logStr+"rn").getBytes());
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Application 代码:
public class CompRegisterApp extends Application
{
private final static String TAG = "ModernFarmApp";
private static Context mContext = null; /**全局Context*/
@Override
public void onCreate()
{
super.onCreate();
mContext = getApplicationContext();
//框架初始化
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG); // 开启debug会影响性能
}
public static Context getmContext() {
return mContext;
}
ArrayList<Activity> list = new ArrayList<Activity>();
public void init() {
// 设置该CrashHandler为程序的默认处理器
CrashHandler catchExcep = new CrashHandler(this);
Thread.setDefaultUncaughtExceptionHandler(catchExcep);
}
/**
* Activity关闭时,删除Activity列表中的Activity对象
*/
public void removeActivity(Activity a) {
list.remove(a);
}
/**
* 向Activity列表中添加Activity对象
*/
public void addActivity(Activity a) {
list.add(a);
}
/**
* 关闭Activity列表中的所有Activity
*/
public void finishActivity() {
/**解决抛出ConcurrentModificationException异常*/
for (int i = 0; i < list.size(); i++ ){
Activity activity = (Activity) list.get(i);
if (activity != null) {
activity.finish();
}
}
// 杀死该应用进程
// android.os.Process.killProcess(android.os.Process.myPid());
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
} else {// android2.1
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
}
}
Application 中主要用到这两段:
CrashHandler catchExcep = new CrashHandler(this);
Thread.setDefaultUncaughtExceptionHandler(catchExcep);
public void finishActivity() {
/**解决抛出ConcurrentModificationException异常*/
for (int i = 0; i < list.size(); i++ ){
Activity activity = (Activity) list.get(i);
if (activity != null) {
activity.finish();
}
}
// 杀死该应用进程
// android.os.Process.killProcess(android.os.Process.myPid());
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
} else {// android2.1
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
}
转载地址:http://blog.csdn.net/konga/article/details/70197030
http://blog.csdn.net/way_ping_li/article/details/8487866
http://www.jb51.net/article/83147.htm
最后
以上就是自由大神为你收集整理的Android logcat信息记录到手机文件的全部内容,希望文章能够帮你解决Android logcat信息记录到手机文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复