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

import org.altusmetrum.altoslib_6.*;

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

public class TelemetryLogger {
	private static final String TAG = "TelemetryLogger";
	private static final boolean D = true;

	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) {
			if (D) Log.d(TAG, "Shutting down Telemetry Logging");
			logger.close();
			logger = null;
		}
	}
	
	void handleExternalStorageState() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (logger == null) {
				if (D) Log.d(TAG, "Starting up Telemetry Logging");
				logger = new AltosLog(link);
			}
		} else {
			if (D) Log.d(TAG, "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);
	}

}