Jeyanth Kumar Jeyanth Kumar - 3 months ago 24
Android Question

Debugging Android Applications Offline

I am developing a application which uses location services. I need to debug the application using

Log.d()
but that needs the device to be connected to the computer all the way. And that's impossible for me to do. I'll be testing the app for about two hours in travelling. I cannot connect it to PC at that time.

Is there any way to save the log in phone and retrieve it later and can see the LOG data.

Answer Source

Introduce your own Logger class, a wrapper for android.util.Log class, which will redirect output both, to file and console:

public class Logger {

    public static PrintWriter printWriter = null;

    private static void init() {
        ...
        // Check if external media is writable
        ...

        if (printWriter == null) {
            try {
                File dir = new File(Environment.getExternalStorageDirectory() + LOG_DIR);
                dir.mkdirs();
                printWriter = new PrintWriter(new FileWriter(new File(dir, LOG_FILE), true));
            }
            catch (IOException e) {
                Log.e(Logger.class.getName(), "initExternal() -> IOException", e);
            }
        }
    }

    private static synchronized int log(int priority, String tag, String msg) {
        int res = Log.println(priority, tag, msg);

        init(); // May be called just once, depending on your requirements

        printWriter.print(tag + "   ");
        printWriter.print(msg + "\r\n");
        printWriter.flush();
        return res;
    }


    // Duplicates of standard android.util.Log methods:
    public static int v(String tag, String msg) {
        return log(Log.VERBOSE, tag, msg);
    }
    public static int v(String tag, String msg, Throwable tr) {
        return log(Log.VERBOSE, tag, msg + '\n' + Log.getStackTraceString(tr));
    }
    public static int d(String tag, String msg) {
        return log(Log.DEBUG, tag, msg);
    }
    public static int d(String tag, String msg, Throwable tr) {
        return log(Log.DEBUG, tag, msg + '\n' + Log.getStackTraceString(tr));
    }

    ...

}