天天看點

Android中級教程之----Log圖文詳解(Log.v,Log.d,Log.i,Log.w,Log.e)

在Android群裡,經常會有人問我,Android Log是怎麼用的,今天我就把從網上以及SDK裡東拼西湊過來,讓大家先一睹為快,希望對大家入門Android Log有一定的幫助.

android.util.Log常用的方法有以下5個:Log.v() Log.d() Log.i() Log.w() 以及 Log.e() 。根據首字母對應VERBOSE,DEBUG,INFO, WARN,ERROR。

1、Log.v 的調試顔色為黑色的,任何消息都會輸出,這裡的v代表verbose啰嗦的意思,平時使用就是Log.v("","");

2、Log.d的輸出顔色是藍色的,僅輸出debug調試的意思,但他會輸出上層的資訊,過濾起來可以通過DDMS的Logcat标簽來選擇.

3、Log.i的輸出為綠色,一般提示性的消息information,它不會輸出Log.v和Log.d的資訊,但會顯示i、w和e的資訊

4、Log.w的意思為橙色,可以看作為warning警告,一般需要我們注意優化Android代碼,同時選擇它後還會輸出Log.e的資訊。

5、Log.e為紅色,可以想到error錯誤,這裡僅顯示紅色的錯誤資訊,這些錯誤就需要我們認真的分析,檢視棧的資訊了。

下面是我做的一個簡單的LogDemo(Step By Step):

Step 1:準備工作(打開LogCat視窗).

 啟動Eclipse,在Window->Show View會出來一個對話框,當我們點選Ok按鈕時,會在控制台視窗出現LogCat視窗

Step 2:建立一個Android工程,命名為LogDemo.

Step 3:設計UI界面,我們在這裡就加了一個Button按鈕(點選按鈕出現Log日志資訊).

Main.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello"

    />

<Button

 android:id="@+id/bt"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:text="Presse Me Look Log"

/>

</LinearLayout>

Step 4:設計主類LogDemo.java,代碼如下:

package com.android.test;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

public class LogDemo extends Activity {

 private static final String ACTIVITY_TAG="LogDemo";

 private Button bt;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //通過findViewById找到Button資源

        bt = (Button)findViewById(R.id.bt);

        //增加事件響應

        bt.setOnClickListener(new Button.OnClickListener(){

    @Override

   public void onClick(View v) {

    Log.v(LogDemo.ACTIVITY_TAG, "This is Verbose.");

    Log.d(LogDemo.ACTIVITY_TAG, "This is Debug.");

    Log.i(LogDemo.ACTIVITY_TAG, "This is Information");

    Log.w(LogDemo.ACTIVITY_TAG, "This is Warnning.");

    Log.e(LogDemo.ACTIVITY_TAG, "This is Error.");

   }

        });

    }

}

Step 5:運作LogDemo工程

當我們點選按鈕時,會觸發事件