Why doesn't “System.out.println” work in Android?

前端 未结 11 709
轮回少年
轮回少年 2020-11-22 07:55

I want to print something in console, so that I can debug it. But for some reason, nothing prints in my Android application.

How do I debug then?

         


        
11条回答
  •  礼貌的吻别
    2020-11-22 08:17

    Correction:

    On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.

    Original:

    There is no console to send the messages to so the System.out.println messages get lost. In the same way this happens when you run a "traditional" Java application with javaw.

    Instead, you can use the Android Log class:

    Log.d("MyApp","I am here");
    

    You can then view the log either in the Logcat view in Eclipse, or by running the following command:

    adb logcat
    

    It's good to get in to the habit of looking at logcat output as that is also where the Stack Traces of any uncaught Exceptions are displayed.

    The first Entry to every logging call is the log tag which identifies the source of the log message. This is helpful as you can filter the output of the log to show just your messages. To make sure that you're consistent with your log tag it's probably best to define it once as a static final String somewhere.

    Log.d(MyActivity.LOG_TAG,"Application started");
    

    There are five one-letter methods in Log corresponding to the following levels:

    • e() - Error
    • w() - Warning
    • i() - Information
    • d() - Debug
    • v() - Verbose
    • wtf() - What a Terrible Failure

    The documentation says the following about the levels:

    Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

提交回复
热议问题