Commit b2700dad authored by Javier Baliosian's avatar Javier Baliosian
Browse files

primera adaptacion del código de LocationTacker de android

parent 57625390
......@@ -5,7 +5,7 @@ android {
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.elbitsalvaje.javier.wifidump"
applicationId "com.elbitsalvaje.wifitracker.TrackerActivity"
minSdkVersion 7
targetSdkVersion 21
versionCode 1
......
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.elbitsalvaje.javier.wifidump" >
package="com.elbitsalvaje.wifitracker" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Permissions for the Location Service -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- give the location tracker ability to induce device insomnia -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:label="@string/app_label"
android:theme="@style/AppTheme" >
<activity
android:name=".wifidumper"
android:label="@string/app_name" >
android:name="com.elbitsalvaje.wifitracker.TrackerActivity"
android:label="@string/app_label" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.elbitsalvaje.wifitracker.TrackerService" />
<activity android:label="@string/settings_menu" android:name="com.elbitsalvaje.wifitracker.SettingsActivity" />
<provider android:name="com.elbitsalvaje.wifitracker.data.TrackerProvider"
android:authorities="com.elbitsalvaje.wifitracker" />
</application>
</manifest>
package com.elbitsalvaje.javier.wifidump;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Environment;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class wifidumper extends Activity {
WifiManager wifiManager;
WifiScanReceiver wifiReceiver;
ListView list;
String wifis[];
String[] positions = new String[6];
static String filename_dump_wifis = "/sdcard/dump_wifis.txt";
OutputStreamWriter myOutWifiDumpWriter;
FileOutputStream fileWifiDumpOut;
static String filename_dump_position = "/sdcard/dump_position.txt";
OutputStreamWriter myOutPositionWriter;
FileOutputStream filePositionOut;
static String filename_dump_GPS_position = "/sdcard/dump_GPS_position.txt";
OutputStreamWriter myOutGPSPositionWriter;
FileOutputStream fileGPSPositionOut;
SensorManager sensorManager;
Sensor sensorAccelerometer;
SensorReceiver positionReceiver;
LocationManager locationManager;
LocationReceiver locationReceiver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifidumper);
list = (ListView) findViewById(R.id.listView1);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WifiScanReceiver();
wifiManager.startScan();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
positionReceiver = new SensorReceiver();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationReceiver = new LocationReceiver();
try {
// file for dumping wifi information
File myFile_wifis = new File(filename_dump_wifis);
myFile_wifis.createNewFile();
fileWifiDumpOut = new FileOutputStream(myFile_wifis);
myOutWifiDumpWriter = new OutputStreamWriter(fileWifiDumpOut);
// file for dumping azimuth, pitch and roll
File myFile_position = new File(filename_dump_position);
myFile_position.createNewFile();
filePositionOut = new FileOutputStream(myFile_position);
myOutPositionWriter = new OutputStreamWriter(filePositionOut);
// file for dumping GPS info
File myFile_GPS_position = new File(filename_dump_GPS_position);
myFile_GPS_position.createNewFile();
fileGPSPositionOut = new FileOutputStream(myFile_GPS_position);
myOutGPSPositionWriter = new OutputStreamWriter(fileGPSPositionOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPause() {
unregisterReceiver(wifiReceiver);
sensorManager.unregisterListener(positionReceiver);
locationManager.removeUpdates(locationReceiver);
try {
myOutWifiDumpWriter.close();
fileWifiDumpOut.close();
myOutPositionWriter.close();
filePositionOut.close();
myOutGPSPositionWriter.close();
fileGPSPositionOut.close();
} catch (IOException e) {
e.printStackTrace();
}
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
sensorManager.registerListener(positionReceiver, sensorAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationReceiver);
super.onResume();
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = wifiManager.getScanResults();
wifis = new String[wifiScanList.size()];
long currentTime = System.currentTimeMillis();
for(int i = 0; i < wifiScanList.size(); i++){
// not using wifiScanList.timestamp because is not available in version 7
wifis[i] = currentTime + "," + wifiScanList.get(i).BSSID + "," + wifiScanList.get(i).level;
// dumps wifi info on file
try {
myOutWifiDumpWriter.append(wifis[i]);
myOutWifiDumpWriter.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
}
// shows wifi info at the screen
//list.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,wifis));
wifiManager.startScan();
}
}
class LocationReceiver implements LocationListener {
@Override
public void onLocationChanged(Location location) {
long time = location.getTime();
float acc = location.getAccuracy();
double lat = location.getLatitude();
double lng = location.getLongitude();
double alt = location.getAltitude();
try {
myOutGPSPositionWriter.append(time + ", " + acc + ", " +
lat + ", " + lng + ", " + alt );
myOutGPSPositionWriter.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
positions[0] = "GPS:";
positions[1] = String.valueOf(time);
positions[2] = String.valueOf(acc);
positions[3] = String.valueOf(lat);
positions[4] = String.valueOf(lng);
positions[5] = String.valueOf(alt);
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, positions));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
class SensorReceiver implements SensorEventListener {
public void onSensorChanged(SensorEvent event) {
/*
* event.values[1]: pitch, rotation around the X axis.
* event.values[0]: azimuth, rotation around the Z axis.
* event.values[2]: roll, rotation around the Y axis.
*/
float valueAzimuth = event.values[0];
float valuePitch = event.values[1];
float valueRoll = event.values[2];
try {
myOutPositionWriter.append(event.timestamp + ", " + valueAzimuth + ", " +
valuePitch + ", " + valueRoll);
myOutPositionWriter.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
// positions[0] = "Position:";
// positions[1] = String.valueOf(valueAzimuth);
// positions[2] = String.valueOf(valuePitch);
// positions[3] = String.valueOf(valueRoll);
//
// list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, positions));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}
package com.elbitsalvaje.wifitracker;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.os.Bundle;
import android.preference.PreferenceActivity;
import com.elbitsalvaje.wifitracker.R;
/**
* Settings preference screen for location tracker
*/
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
\ No newline at end of file
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.elbitsalvaje.wifitracker;
import com.elbitsalvaje.wifitracker.R;
import com.elbitsalvaje.wifitracker.data.DateUtils;
import com.elbitsalvaje.wifitracker.data.TrackerDataHelper;
import com.elbitsalvaje.wifitracker.data.TrackerListHelper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* Activity for location tracker service
*
* Contains facilities for starting and
* stopping location tracker service, as well as displaying the current location
* data
*
* Future enhancements:
* - export data as dB
* - enable/disable "start service" and "stop service" menu items as
* appropriate
*/
public class TrackerActivity extends ListActivity {
static final String LOG_TAG = "LocationTracker";
private TrackerListHelper mDataHelper;
/**
* Retrieves and displays the currently logged location data from file
*
* @param icicle
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mDataHelper = new TrackerListHelper(this);
mDataHelper.bindListUI(R.layout.entrylist_item);
}
/**
* Builds the menu
*
* @param menu - menu to add items to
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_wifidumper, menu);
return true;
}
/**
* Handles menu item selection
*
* @param item - the selected menu item
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.start_service_menu: {
startService(new Intent(TrackerActivity.this,
TrackerService.class));
break;
}
case R.id.stop_service_menu: {
stopService(new Intent(TrackerActivity.this,
TrackerService.class));
break;
}
case R.id.settings_menu: {
launchSettings();
break;
}
case R.id.export_kml: {
exportKML();
break;
}
case R.id.export_csv: {
exportCSV();
break;
}
case R.id.clear_data_menu: {
clearData();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void clearData() {
Runnable clearAction = new Runnable() {
public void run() {
TrackerDataHelper helper =
new TrackerDataHelper(TrackerActivity.this);
helper.deleteAll();
}
};
showConfirm(R.string.delete_confirm, clearAction);
}
private void showConfirm(int textId, final Runnable onConfirmAction) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle(R.string.confirm_title);
dialogBuilder.setMessage(textId);
dialogBuilder.setPositiveButton(android.R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onConfirmAction.run();
}
});
dialogBuilder.setNegativeButton(android.R.string.cancel,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
dialogBuilder.show();
}
private void exportCSV() {
String exportFileName = getUniqueFileName("csv");
exportFile(null, exportFileName, new TrackerDataHelper(this,
TrackerDataHelper.CSV_FORMATTER));
}
private void exportKML() {
String exportFileName = getUniqueFileName(
LocationManager.NETWORK_PROVIDER + ".kml");
exportFile(LocationManager.NETWORK_PROVIDER, exportFileName,
new TrackerDataHelper(this, TrackerDataHelper.KML_FORMATTER));
exportFileName = getUniqueFileName(
LocationManager.GPS_PROVIDER + ".kml");
exportFile(LocationManager.GPS_PROVIDER, exportFileName,
new TrackerDataHelper(this, TrackerDataHelper.KML_FORMATTER));
}
private void exportFile(String tagFilter,
String exportFileName,
TrackerDataHelper trackerData) {
BufferedWriter exportWriter = null;
Cursor cursor = trackerData.query(tagFilter);
try {
exportWriter = new BufferedWriter(new FileWriter(exportFileName));
exportWriter.write(trackerData.getOutputHeader());
String line = null;
while ((line = trackerData.getNextOutput(cursor)) != null) {
exportWriter.write(line);
}
exportWriter.write(trackerData.getOutputFooter());
Toast.makeText(this, "Successfully exported data to " +
exportFileName, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error exporting file: " +
e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Error exporting file", e);
} finally {
closeWriter(exportWriter);
if (cursor != null) {
cursor.close();
}
}
}
private void closeWriter(Writer exportWriter) {
if (exportWriter != null) {
try {
exportWriter.close();
} catch (IOException e) {
Log.e(LOG_TAG, "error closing file", e);
}
}
}
private String getUniqueFileName(String ext) {
File dir = new File(Environment.getExternalStorageDirectory() + "/locationtracker");
if (!dir.exists()) {
dir.mkdir();
}
return dir + "/tracking-" + DateUtils.getCurrentTimestamp() + "." + ext;
}
private void launchSettings() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(this, SettingsActivity.class);
startActivity(settingsIntent);
}
}
package com.elbitsalvaje.wifitracker;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");