在textview中顯示logcat日志 – JAVA編程語言程序開發技術文章

我們在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” />

發佈留言