[Android] アプリ・サービス内でのlogcat読取
2017/11/23
アプリやサービス内でlogcatを読み取ることが出来ます。
今回はAndroid4.1以降でのlogcat出力について。
※Android4.1以降では、自アプリのlogcatしか覗けなくなっています。
パーミッションは不要。
Thread logcatThread = null;
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    if (logcatThread == null)
    {
        logcatThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                String line;
                Process process;
                BufferedReader reader = null;
                try
                {
                    process = Runtime.getRuntime().exec(new String[] { "logcat", "-v", "time", "*:V" });
                    reader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);
                    while (true)
                    {
                        //==== ログ読み込み ====//
                        line = reader.readLine();
                        if ((line == null) || (line.length() == 0))
                        {
                            //-==- データ無し -==-//
                            try
                            {
                                Thread.sleep(100);
                            }
                            catch (InterruptedException e)
                            {
                            }
                            continue;
                        }
                        line += "\r\n";
                        // 読み取ったログに対して任意の処理を行う。
                    }
                }
                catch (IOException e)
                {
                }
                finally
                {
                    if (reader != null)
                    {
                        try
                        {
                            reader.close();
                        }
                        catch (IOException e)
                        {
                        }
                    }
                }
                logcatThread = null;
            }
        });
        logcatThread.start();
    }
}