summaryrefslogtreecommitdiffstats
path: root/app/src/main/java/com/xc3fff0e/xmanager/xManagerLogger.java
blob: 24e49ff17a20ff38ad5423ddb305a4e12730ee5c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.xc3fff0e.xmanager;

import android.content.Intent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;
import android.util.Log;

public class xManagerLogger {
	
	private static Thread loggerThread = new Thread() {
		@Override
		public void run() {
			isRunning = true;
			
			try {
				Runtime.getRuntime().exec("logcat -c");
				Process process = Runtime.getRuntime().exec("logcat");
				
				try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
					String logTxt = bufferedReader.readLine();
					do {
						broadcastLog(logTxt);
					} while (isRunning && ((logTxt = bufferedReader.readLine()) != null));
					
					// Thread got stopped, restart if not stopping wantedly
					if (isRunning) {
						broadcastLog("Logger got killed. Restarting.");
						startLogging();
					} else {
						broadcastLog("Logger stopped.");
					}
				}
			} catch (Exception e) {
				broadcastLog(e.toString());
			}
		}
	};
	
	private static volatile boolean isRunning = false;
	
	public static void startLogging() {
		if (!isRunning) {
			loggerThread.start();
		} else {
			throw new IllegalStateException("Logger already running");
		}
	}
	
	public static void broadcastLog(String log) {
		Context context = xManager.getContext();
		
		Intent intent = new Intent();
		intent.setAction("com.xc3fff0e.xmanager.ACTION_NEW_DEBUG_LOG");
		intent.putExtra("log", log);
		intent.putExtra("packageName", context.getPackageName());
		context.sendBroadcast(intent);
	}
	
	public static void stopLogging() {
		if (isRunning) {
			isRunning = false;
			broadcastLog("Stopping logger by user request.");
		} else {
			throw new IllegalStateException("Logger not running");
		}
	}
}