summaryrefslogtreecommitdiff
path: root/altosdroid/src/org/altusmetrum/AltosDroid/TelemetryLogger.java
blob: c379d3d84af153f77bd68f32eb5866d62eea4c52 (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
package org.altusmetrum.AltosDroid;

import org.altusmetrum.altoslib_11.*;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;

public class TelemetryLogger {
	private Context   context = null;
	private AltosLink link    = null;
	private AltosLog  logger  = null;

	private BroadcastReceiver mExternalStorageReceiver;

	public TelemetryLogger(Context in_context, AltosLink in_link) {
		context = in_context;
		link    = in_link;

		startWatchingExternalStorage();
	}

	public void stop() {
		stopWatchingExternalStorage();
		close();
	}

	private void close() {
		if (logger != null) {
			AltosDebug.debug("Shutting down Telemetry Logging");
			logger.close();
			logger = null;
		}
	}

	void handleExternalStorageState() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (logger == null) {
				AltosDebug.debug("Starting up Telemetry Logging");
				logger = new AltosLog(link);
			}
		} else {
			AltosDebug.debug("External Storage not present - stopping");
			close();
		}
	}

	void startWatchingExternalStorage() {
		mExternalStorageReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				handleExternalStorageState();
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		filter.addAction(Intent.ACTION_MEDIA_REMOVED);
		context.registerReceiver(mExternalStorageReceiver, filter);
		handleExternalStorageState();
	}

	void stopWatchingExternalStorage() {
		context.unregisterReceiver(mExternalStorageReceiver);
	}

}