Programing

“System.out.println”이 Android에서 작동하지 않는 이유는 무엇입니까?

lottogame 2020. 5. 18. 08:03
반응형

“System.out.println”이 Android에서 작동하지 않는 이유는 무엇입니까?


콘솔에서 무언가를 인쇄하여 디버깅 할 수 있습니다. 그러나 어떤 이유로 든 내 안드로이드 응용 프로그램에는 아무것도 인쇄되지 않습니다.

그런 다음 어떻게 디버깅합니까?

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");
    }

보정:

에뮬레이터에서 대부분의 장치 System.out.println는 LogCat로 리디렉션되고를 사용하여 인쇄됩니다 Log.i(). 매우 오래된 또는 사용자 정의 Android 버전에서는 그렇지 않을 수 있습니다.

기발한:

메시지를 보낼 콘솔이 없으므로 System.out.println메시지가 손실됩니다. 같은 방법으로을 사용하여 "전통적인"Java 응용 프로그램을 실행할 때 이런 일이 발생합니다 javaw.

대신 Android Log클래스를 사용할 수 있습니다 .

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

그런 다음 Eclipse Logcat 보기에서 또는 다음 명령을 실행하여 로그를 볼 수 있습니다 .

adb logcat

포착되지 않은 예외의 스택 추적도 표시되므로 logcat 출력을 보는 습관을들이는 것이 좋습니다.

모든 로깅 호출의 첫 번째 항목은 로그 메시지의 소스를 식별하는 로그 태그입니다. 이는 메시지 출력 만 표시하도록 로그 출력을 필터링 할 때 유용합니다. 로그 태그와 일관성을 유지하려면 static final String어딘가에 한 번 정의하는 것이 가장 좋습니다 .

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

Log다음 레벨 해당하는 5 가지 1 문자 방법이 있습니다.

  • e() -오류
  • w() -경고
  • i() -정보
  • d() -디버그
  • v() -상세
  • wtf() -끔찍한 실패

문서는 레벨에 대한 다음 말한다 :

Verbose는 개발 중을 제외하고는 응용 프로그램으로 컴파일해서는 안됩니다. 디버그 로그는 컴파일되지만 런타임에 제거됩니다. 오류, 경고 및 정보 로그는 항상 유지됩니다.


Log 클래스를 사용하십시오 . LogCat으로 볼 수있는 출력


그렇습니다. 에뮬레이터를 사용하는 경우 System.out태그 아래의 Logcat보기에 표시됩니다 . 무언가를 쓰고 에뮬레이터에서 사용해보십시오.


물론 logcat에서 결과를 보려면 Log level을 최소한 "Info"( logcat 의 log level)로 설정해야합니다 . 그렇지 않으면, 나에게 일어난 것처럼, 당신은 당신의 결과를 볼 수 없습니다.


실제로 작동하려면 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 클래스 :

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;
        }
    }
}

There is no place on your phone that you can read the 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! :)


it is not displayed in your application... it is under your emulator's logcat


System.out.println("...") is displayed on the Android Monitor in Android Studio


I'll leave this for further visitors as for me it was something about the main thread being unable to 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");


최근에 Android Studio 3.3에서 동일한 문제가 발견되었습니다. 다른 Android 스튜디오 프로젝트를 닫고 Logcat이 작동하기 시작했습니다. 위의 대답은 전혀 논리적이지 않습니다.

참고 URL : https://stackoverflow.com/questions/2220547/why-doesnt-system-out-println-work-in-android

반응형