Monday, April 23, 2012

Reading logcat content in android

2 steps to do this.

1. Edit your manifest file. and mention permission android.permission.READ_LOGS


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.readlogcatTest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_LOGS" />
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ReadLogcatActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



2. Create Activity and put following code in onCreate() method or where you want



package com.readlogcatTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReadLogcatActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try {
            Process process = Runtime.getRuntime().exec("logcat -d");
            BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
 
            StringBuilder log=new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                              log.append(line);
            }
            
            TextView tv = (TextView)findViewById(R.id.logcat);
            tv.setText(log.toString());
            bufferedReader.close();
            process.destroy();
          } catch (IOException e) {e.printStackTrace();
          }
    }
}




No comments:

Post a Comment