Java 为什么“System.out.println”在Android 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2220547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't "System.out.println" work in Android?
提问by TIMEX
I want to print something in console, so that I can debug it. But for some reason, nothing prints in my Android application.
我想在控制台中打印一些东西,以便我可以调试它。但出于某种原因,我的 Android 应用程序中没有打印任何内容。
How do I debug then?
那我该如何调试呢?
public class HelloWebview extends Activity {
WebView webview;
private static final String LOG_TAG = "WebViewDemo";
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyWebChromeClient());
webview.loadUrl("http://example.com/");
System.out.println("I am here");
}
采纳答案by Dave Webb
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.
在模拟器和大多数设备上System.out.println
被重定向到 LogCat 并使用Log.i()
. 这可能不适用于非常旧的或自定义的 Android 版本。
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
.
没有控制台可以发送消息,因此System.out.println
消息会丢失。以同样的方式,当您使用javaw
.
Instead, you can use the Android Log
class:
相反,您可以使用AndroidLog
类:
Log.d("MyApp","I am here");
You can then view the log either in the Logcatview in Eclipse, or by running the following command:
然后,您可以在 Eclipse的Logcat视图中查看日志,或者运行以下命令:
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.
养成查看 logcat 输出的习惯很好,因为这也是显示任何未捕获异常的堆栈跟踪的地方。
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.
每个日志记录调用的第一个条目是标识日志消息来源的日志标记。这很有用,因为您可以过滤日志的输出以仅显示您的消息。为了确保您与您的日志标签一致,最好将其定义为static final String
某个地方。
Log.d(MyActivity.LOG_TAG,"Application started");
There are five one-letter methods in Log
corresponding to the following levels:
一字法有五种,分别Log
对应以下等级:
e()
- Errorw()
- Warningi()
- Informationd()
- Debugv()
- Verbosewtf()
- What a Terrible Failure
e()
- 错误w()
- 警告i()
- 信息d()
- 调试v()
- 详细wtf()
- 多么可怕的失败
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.
除非在开发期间,否则永远不应将 Verbose 编译到应用程序中。调试日志被编译但在运行时被剥离。错误、警告和信息日志始终保留。
回答by kaushikSuman
Yes it does. If you're using the emulator, it will show in the Logcat view under the System.out
tag. Write something and try it in your emulator.
是的,它确实。如果您使用的是模拟器,它将显示在 Logcat 视图中的System.out
标签下。写一些东西并在你的模拟器中尝试。
回答by Marc
Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.
当然,要在logcat中看到结果,至少应该将Log级别设置为“Info”(logcat中的Log级别);否则,就像我遇到的那样,您将看不到输出。
回答by Valentin Filyov
There is no place on your phone that you can read the System.out.println();
手机上没有地方可以阅读 System.out.println();
Instead, if you want to see the result of something either look at your logcat/console
window or make a Toast
or a Snackbar
(if you're on a newer device) appear on the device's screen with the message :)
That's what i do when i have to check for example where it goes in a switch case
code! Have fun coding! :)
相反,如果您想查看某些内容的结果,请查看您的logcat/console
窗口或在设备屏幕上显示一个Toast
或一个Snackbar
(如果您使用的是较新的设备)并显示消息:) 这就是我必须检查时所做的例如它在switch case
代码中的位置!玩得开心编码!:)
回答by 7heaven
if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:
如果你真的需要 System.out.println 工作(例如,它是从第三方库调用的)。您可以简单地使用反射来更改 System.class 中的字段:
try{
Field outField = System.class.getDeclaredField("out");
Field modifiersField = Field.class.getDeclaredField("accessFlags");
modifiersField.setAccessible(true);
modifiersField.set(outField, outField.getModifiers() & ~Modifier.FINAL);
outField.setAccessible(true);
outField.set(null, new PrintStream(new RedirectLogOutputStream());
}catch(NoSuchFieldException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
RedirectLogOutputStream class:
RedirectLogOutputStream 类:
public class RedirectLogOutputStream extends OutputStream{
private String mCache;
@Override
public void write(int b) throws IOException{
if(mCache == null) mCache = "";
if(((char) b) == '\n'){
Log.i("redirect from system.out", mCache);
mCache = "";
}else{
mCache += (char) b;
}
}
}
回答by Wesos de Queso
System.out.println("...") is displayed on the Android Monitor in Android Studio
System.out.println("...") 显示在 Android Studio 的 Android Monitor 上
回答by Nut eater
I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println
.
我会把这个留给更多的访问者,因为对我来说,这是关于主线程无法做到的System.out.println
。
public class LogUtil {
private static String log = "";
private static boolean started = false;
public static void print(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log
log += s;
}
public static void println(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log with a newline.
//NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
log += (s.endsWith("\n") )? s : (s + "\n");
}
private static void start() {
//Creates a new Thread responsible for showing the logs.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
//Execute 100 times per second to save CPU cycles.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//If the log variable has any contents...
if(!log.isEmpty()) {
//...print it and clear the log variable for new data.
System.out.print(log);
log = "";
}
}
}
});
thread.start();
started = true;
}
}
Usage: LogUtil.println("This is a string");
用法: LogUtil.println("This is a string");
回答by Ronak Desai
Recently I noticed the same issue in Android Studio 3.3. I closed the other Android studio projects and Logcat started working. The accepted answer above is not logical at all.
最近我在 Android Studio 3.3 中发现了同样的问题。我关闭了其他 Android Studio 项目,Logcat 开始工作。上面接受的答案根本不合逻辑。
回答by ALSP
it is not displayed in your application... it is under your emulator's logcat
它没有显示在您的应用程序中...它在您的模拟器的 logcat 下