2011年4月8日金曜日

AndroidでSystem.outとSystem.errをLogに転送する

Androidでは、System.outとSystem.errがLogに転送されているけれど、
任意のプライオリティと任意のタグでLogに転送するコードを作ってみた。

ついでに、はじめてGistを使ってみた。

Gistで保存するコードの先頭には、コピーライトとか書かない方がいいのかもなぁ。

/* RuntimeInit.java
* My favorite initialization code for Android applications.
*
* Copyright (C) 2011 TAKUMAKei
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blogspot.takumakei.gist;
import java.io.PrintStream;
import android.util.Log;
/**
* The class for runtime initialization.
*
* <code>
* class YourActivity extends Activity {
* static {
* RuntimeInit.setOut(android.util.Log.INFO, "Kei");
* RuntimeInit.setErr(android.util.Log.ERROR, "Kei");
* }
* }
* </code>
*/
public class RuntimeInit {
/**
* Redirect 'System.out' to android.util.Log with any priority and tag you want.
*
* @param priority from {@link android.util.Log}
* @param tag to log
*/
public static void setOut(int priority, String tag) {
try {
System.setOut(getAndroidPrintStream(priority, tag));
} catch (Exception e) {
Log.e(tag, "RuntimeInit.setOut", e);
}
}
/**
* Redirect 'System.err' to android.util.Log with any priority and tag you want.
*
* @param priority from {@link android.util.Log}
* @param tag to log
*/
public static void setErr(int priority, String tag) {
try {
System.setErr(getAndroidPrintStream(priority, tag));
} catch (Exception e) {
Log.e(tag, "RuntimeInit.setErr", e);
}
}
/**
* Create a new logging print stream.
*
* @param priority from {@link android.util.Log}
* @param tag to log
* @return A print stream which logs output line by line.
* @throws Exception thrown when the com.android.internal.os.AndroidPrintStream was not found.
*/
public static PrintStream getAndroidPrintStream(int priority, String tag) throws Exception {
return (PrintStream) (Class
.forName("com.android.internal.os.AndroidPrintStream")
.getConstructor(int.class, String.class)
.newInstance(priority, tag));
}
}
view raw RutimeInit.java hosted with ❤ by GitHub


おもいっきりプライベートなAPI使ってるから良くない子に分類されるだろう。

0 件のコメント:

コメントを投稿