`
天涯海角tour
  • 浏览: 170162 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

android 程序日志记录

阅读更多
 要加入权限 
    <uses-permission android:name="android.permission.READ_LOGS" />
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Demo8Activity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    String filenameTemp  = Environment.getExternalStorageDirectory().toString()+ "/app.txt";// 照片文件绝对路径
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) this.findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    //例子
    try
    {
      int i=10/0;
    }catch(Exception e)
    {
     Log.e("Android", e.getMessage());
         }
    Process mLogcatProc = null;
    BufferedReader reader = null;
    try
    {
            mLogcatProc = Runtime.getRuntime().exec(new String[]
                    {"logcat", "-d", "AndroidRuntime:E Android:V *:S" });//Android为你的Tag
            reader = new BufferedReader(new InputStreamReader
    (mLogcatProc.getInputStream()));
            String line;
            final StringBuilder log = new StringBuilder();
            String separator = System.getProperty("line.separator"); 
            while ((line = reader.readLine()) != null)
            {
                    log.append(line);
                    log.append(separator);
            }
            CreateText();
            print(log.toString());
            // do whatever you want with the log.  I'd recommend using Intents to create an email
    }
    catch (IOException e)
    {
    }
    finally
    {
            if (reader != null)
                    try
                    {
                            reader.close();
                    }
                    catch (IOException e)
                    {
                    }
    } 
   }
         
  }); 
        
        
    }
   
    //创建文件夹及文件 
    public  void CreateText() throws IOException { 
        File dir = new File(filenameTemp); 
        if (!dir.exists()) { 
              try { 
                  //在指定的文件夹中创建文件 
                  System.out.println(dir.createNewFile()+"---------------------");;
            } catch (Exception e) { 
            } 
        } 
 
    } 
     
    //向已创建的文件中写入数据 
    public  void print(String str) { 
        FileWriter fw = null; 
        BufferedWriter bw = null; 
        String datetime = ""; 
        try { 
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd" + " " 
                    + "hh:mm:ss"); 
            datetime = tempDate.format(new java.util.Date()).toString(); 
            fw = new FileWriter(filenameTemp, true);// 
            // 创建FileWriter对象,用来写入字符流 
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出 
            String myreadline = datetime + "[]" + str; 
             
            bw.write(myreadline + "\n"); // 写入文件 
            bw.newLine(); 
            bw.flush(); // 刷新该流的缓冲 
            bw.close(); 
            fw.close(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
            try { 
                bw.close(); 
                fw.close(); 
            } catch (IOException e1) { 
                // TODO Auto-generated catch block 
            } 
        } 
    } 
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  
 } 
   /**
     * 监听退出事件
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // 确认对话框
        final AlertDialog isExit = new AlertDialog.Builder(this).create();
        // 对话框标题
        isExit.setTitle("系统提示");
        // 对话框消息
        isExit.setMessage("确定要退出吗");
        // 实例化对话框上的按钮点击事件监听
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          switch (which) {
          case AlertDialog.BUTTON1:// "确认"按钮退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
           break;
          case AlertDialog.BUTTON2:// "取消"第二个按钮取消对话框
           isExit.cancel();
           break;
          default:
           break;
          }
         }
        };
        // 注册监听
        isExit.setButton("确定", listener);
        isExit.setButton2("取消", listener);
        // 显示对话框
        isExit.show();
        return false;
       }
       return false;
      }
}

日志输出到文件是


2012-02-28 05:06:00[]--------- beginning of /dev/log/system--------- beginning of /dev/log/mainE/AndroidRuntime(22045): divide by zero
关于logcat 命令的用法可以查看

http://developer.android.com/guide/developing/tools/adb.html#usinglogcat

 

Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

adb logcat ActivityManager:I MyApp:D *:S
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics