Posted on 2011-03-09 13:44
andteamroid 阅读(5680)
评论(3) 编辑 收藏
我们在Eclipse中经常使用Logcat窗口查看日志信息,不过其实也可以在手机上显示日志。下面的例子就是在textview中显示logcat日志。
java代码如下:
1
2 package LogcatTextView.com;
3
4 import java.io.BufferedReader;
5 import java.io.IOException;
6 import java.io.InputStreamReader;
7
8 import android.app.Activity;
9 import android.os.Bundle;
10 import android.widget.ScrollView;
11 import android.widget.TextView;
12
13 public class LogcatTextView extends Activity {
14 /** Called when the activity is first created. */
15 @Override
16 public void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.main);
19
20 try {
21
22 Process process = Runtime.getRuntime().exec("logcat -d");
23
24 BufferedReader bufferedReader = new BufferedReader(
25
26 new InputStreamReader(process.getInputStream()));
27
28 StringBuilder log = new StringBuilder();
29
30 String line;
31
32 while ((line = bufferedReader.readLine()) != null) {
33
34 log.append(line);
35
36 }
37
38 TextView tv = (TextView) findViewById(R.id.tvLogcat);
39
40 tv.setText(log.toString());
41
42 final ScrollView scrollView = (ScrollView) findViewById(R.id.scrlLogcat);
43
44 scrollView.post(new Runnable() {
45 @Override
46 public void run() {
47 scrollView.fullScroll(ScrollView.FOCUS_DOWN);
48 }
49 });
50
51 } catch (IOException e) {
52
53 }
54 }
55 }
不要忘记加上权限
<uses-permission android:name="android.permission.READ_LOGS" />