diff --git a/pals-lib.iml b/Pals.iml similarity index 71% rename from pals-lib.iml rename to Pals.iml index dc4a23a..532c29a 100644 --- a/pals-lib.iml +++ b/Pals.iml @@ -1,5 +1,5 @@ - + diff --git a/README.md b/README.md index 247951b..a80f7cc 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,148 @@ # Privacy Aware Location Service Library +[![Download](https://api.bintray.com/packages/bestog/pals/pals/images/download.svg)](https://bintray.com/bestog/pals/pals/_latestVersion) [![API](https://img.shields.io/badge/API-11%2B-green.svg)](https://github.com/bestog/pals-lib/tree/master) +__Privacy Aware Location Service Library for Android -- MLS, OpenCellID, OpenBMap and OpenWLANMap__ -GPS is the most common approach to locate a smartphone-user. The GPS location is determined in Android by Google services. Google stores user profiles about their movement. Thus privacy is not protected! +The GPS localization is realized in Android through a Google service. Google can thereby save user profiles and track the movements of the user. This library prevents the localization on Google interface and uses only free-usable anonymous location-services. +Data on the surrounding wireless networks and cell towers are sent to the location-service. As a result, you get the calculated approximate GPS location of the user. -This library uses location-services to treat the data anonymous. These can be add to your project as a library. +_Be clever and keep your private data anonymous!_ -__Pull Requests are welcome!__ +__Pull-Requests are allowed and encouraged!__ ## Getting Started -1. Download the [latest version](https://github.com/bestog/pals-lib/releases) from GitHub -2. Copy the `palslib.jar` file in your `/libs/`-directory -3. Add this library to your dependencies -4. Ready! + +__Maven__ +``` + + com.bestog.pals + pals + 2.0 + pom + +``` + +__Gradle__ +``` +compile 'com.bestog.pals:pals:2.0' +``` ## Usage +__Permissions (AndroidManifest)__ +``` + + + +// Only for submit-request + +``` + +__Basics__ ```java // Initialize Pals -Pals pals = new Pals(Context ctx); - +Pals pals = new Pals(context); // Enable Provider pals.enableProvider(LocationProvider.PROVIDER_MOZILLA); pals.enableProvider(LocationProvider.PROVIDER_OPENBMAP); ... - -// Request +``` +__Request__ +A request that returns the current approximate position of the user as a result. +```java pals.request(new IRequest() { @Override public void onComplete(GeoResult result, boolean valid) { - // Result - Example ----------------- - // double lat = result.getLatitude(); - // double lon = result.getLongitude(); - // int lat = result.getAccuracy(); - // boolean validRequest = valid; + // Result - Example ----------------- + double lat = result.getLatitude(); + double lon = result.getLongitude(); + int acc = result.getAccuracy(); + boolean validRequest = valid; // ---- YOUR CODE ------------------ } }); ``` +__Submit__ +To guarantee accurate position of a user, the database of location-services with new data needs to be filled. +Help us with it and collect new data! +```java +pals.submit(new ISubmit() { + @Override + public void onComplete(boolean valid) { + // Result - Example ----------- + boolean validSubmit = valid; + // ---- YOUR CODE ------------ + } +}); +``` ## Provider + +__Mozilla Location Service__ `LocationProvider.PROVIDER_MOZILLA` +[+] Request +[+] Submit +__OpenBMap__ `LocationProvider.PROVIDER_OPENBMAP` +[+] Request +[-] Submit -`LocationProvider.PROVIDER_GOOGLE` - +__OpenCellID__ `LocationProvider.PROVIDER_OPENCELLID` +[+] Request +[-] Submit +__OpenMap__ `LocationProvider.PROVIDER_OPENMAP` +[+] Request +[-] Submit + +__Google Geolocation__ +`LocationProvider.PROVIDER_GOOGLE` +[+] Request +[-] Submit ## Functions #### enableProvider -Enable a provider for the geolocation. +Enable a location-provider for the geolocation. ```java -enableProvider(String provider); +void enableProvider(String provider); ``` #### disableProvider -Disable a provider for the geolocation. +Disable a location-provider for the geolocation. ```java -disableProvider(String provider); +void disableProvider(String provider); +``` + +#### enabledProvider +Get all enabled location-provider as a comma-seperated string +```java +String enabledProvider(); ``` #### request Executes a request and sends at the end the result to the listener. ```java -request(IRequest listener); +void request(IRequest listener); +``` + +#### submit +Executes a submit, collect data from current position and send to a location-provider. +```java +void submit(ISubmit listener); ``` #### isProviderEnabled -Is LocationProvider enabled? +Is the specific location-provider enabled? ```java -isProviderEnabled(String provider); +boolean isProviderEnabled(String provider); ``` + +#### setTrilaterateAlg +Set a specific algorithm for the calculation +```java +void setTrilaterateAlg(String alg); +``` \ No newline at end of file diff --git a/app/app.iml b/app/app.iml index 7737c88..e8c320a 100644 --- a/app/app.iml +++ b/app/app.iml @@ -1,5 +1,5 @@ - + @@ -20,7 +20,6 @@ @@ -48,6 +47,7 @@ + @@ -55,6 +55,7 @@ + @@ -62,6 +63,7 @@ + @@ -69,6 +71,7 @@ + @@ -76,33 +79,37 @@ - + + + + + - - - + - - - + - - + + + + + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 5d65790..5f9e5de 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,30 +1,25 @@ -apply plugin: 'com.android.library' +apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" + defaultConfig { + applicationId "com.bestog.palssample" minSdkVersion 11 targetSdkVersion 23 + versionCode 1 + versionName "1.0" } - lintOptions { - abortOnError false + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } } } dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') -} - -task deleteOldJar(type: Delete) { - delete 'release/AndroidPlugin.jar' + compile project(':pals') + compile 'com.android.support:appcompat-v7:23.4.0' } - -task exportJar(type: Copy) { - from('build/intermediates/bundles/release/') - into('release/') - include('classes.jar') - rename('classes.jar', 'palslib.jar') -} - -exportJar.dependsOn(deleteOldJar, build) diff --git a/app/src/main/java/com/bestog/palssample/MainActivity.java b/app/src/main/java/com/bestog/palssample/MainActivity.java new file mode 100644 index 0000000..22568c5 --- /dev/null +++ b/app/src/main/java/com/bestog/palssample/MainActivity.java @@ -0,0 +1,78 @@ +package com.bestog.palssample; + +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.TextView; + +import com.bestog.pals.Pals; +import com.bestog.pals.interfaces.IRequest; +import com.bestog.pals.interfaces.ISubmit; +import com.bestog.pals.provider.LocationProvider; +import com.bestog.pals.utils.GeoResult; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +public class MainActivity extends AppCompatActivity { + + private Pals pals; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + pals = new Pals(this); + pals.enableProvider(LocationProvider.PROVIDER_MOZILLA); + pals.enableProvider(LocationProvider.PROVIDER_OPENBMAP); + pals.enableProvider(LocationProvider.PROVIDER_GOOGLE); + pals.enableProvider(LocationProvider.PROVIDER_OPENMAP); + process(); + } + + private void process() { + final TextView resultat = (TextView) findViewById(R.id.result); + if (resultat != null) { + resultat.setText(""); + } + pals.request(new IRequest() { + @Override + public void onComplete(GeoResult result, boolean valid) { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss", Locale.GERMAN); + String out = String.format("Lat: %1$s\nLon: %2$s\nAcc: %3$s\n\nTime: %4$s", result.getLatitude(), result.getLongitude(), result.getAccuracy(), sdf.format(new Date())); + if (resultat != null) { + resultat.setText(out); + } + } + }); + final TextView submit = (TextView) findViewById(R.id.submit); + pals.submit(new ISubmit() { + @Override + public void onComplete(boolean valid) { + if (submit != null) { + submit.setText((valid) ? "Submit success" : "Submit error"); + } + } + }); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.refresh: + process(); + return true; + } + return super.onOptionsItemSelected(item); + } + + +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..3b1505d --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/menu/main.xml b/app/src/main/res/menu/main.xml new file mode 100644 index 0000000..4d2ac19 --- /dev/null +++ b/app/src/main/res/menu/main.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..cde69bc Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c133a0c Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..bfa42f0 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..324e72c Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..aee44e1 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..3ab3e9c --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..2a6a301 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + Pals Example + Refresh + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..5885930 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/build.gradle b/build.gradle index 86ec806..7c69cc9 100644 --- a/build.gradle +++ b/build.gradle @@ -1,18 +1,22 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:2.0.0-beta5' - } + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.2' + classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } } allprojects { - repositories { - jcenter() - } + repositories { + jcenter() + } } task clean(type: Delete) { - delete rootProject.buildDir + delete rootProject.buildDir } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 05ef575..13372ae 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index dd66f16..122a0dc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Thu Feb 18 12:01:21 CET 2016 +#Mon Dec 28 10:00:20 PST 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/jcenter-bintray.gradle b/jcenter-bintray.gradle new file mode 100644 index 0000000..31cd053 --- /dev/null +++ b/jcenter-bintray.gradle @@ -0,0 +1,59 @@ +apply plugin: 'com.jfrog.bintray' + +version = libraryVersion + +if (project.hasProperty("android")) { // Android libraries + task sourcesJar(type: Jar) { + classifier = 'sources' + from android.sourceSets.main.java.srcDirs + } + + task javadoc(type: Javadoc) { + source = android.sourceSets.main.java.srcDirs + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) + } +} else { // Java libraries + task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource + } +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +artifacts { + archives javadocJar + archives sourcesJar +} + +// Bintray +Properties properties = new Properties() +properties.load(project.rootProject.file('local.properties').newDataInputStream()) + +bintray { + user = properties.getProperty("bintray.user") + key = properties.getProperty("bintray.apikey") + + configurations = ['archives'] + pkg { + repo = bintrayRepo + name = bintrayName + desc = libraryDescription + websiteUrl = siteUrl + vcsUrl = gitUrl + licenses = allLicenses + publish = true + publicDownloadNumbers = true + version { + desc = libraryDescription + gpg { + sign = true //Determines whether to GPG sign the files. The default is false + passphrase = properties.getProperty("bintray.gpg.password") + //Optional. The passphrase for GPG signing' + } + } + } +} \ No newline at end of file diff --git a/jcenter-install.gradle b/jcenter-install.gradle new file mode 100644 index 0000000..cdb363c --- /dev/null +++ b/jcenter-install.gradle @@ -0,0 +1,42 @@ +apply plugin: 'com.github.dcendents.android-maven' + +group = publishedGroupId // Maven Group ID for the artifact + +install { + repositories.mavenInstaller { + // This generates POM.xml with proper parameters + pom { + project { + packaging 'aar' + groupId publishedGroupId + artifactId artifact + + // Add your description here + name libraryName + description libraryDescription + url siteUrl + + // Set your license + licenses { + license { + name licenseName + url licenseUrl + } + } + developers { + developer { + id developerId + name developerName + email developerEmail + } + } + scm { + connection gitUrl + developerConnection gitUrl + url siteUrl + + } + } + } + } +} \ No newline at end of file diff --git a/pals/.gitignore b/pals/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/pals/.gitignore @@ -0,0 +1 @@ +/build diff --git a/pals/build.gradle b/pals/build.gradle new file mode 100644 index 0000000..4d0c7d5 --- /dev/null +++ b/pals/build.gradle @@ -0,0 +1,40 @@ +apply plugin: 'com.android.library' + +ext { + bintrayRepo = 'pals' + bintrayName = 'pals' + + publishedGroupId = 'com.bestog.pals' + libraryName = 'PALS' + artifact = 'pals' + + libraryDescription = 'Privacy Aware Location Service Library for Android' + libraryVersion = '2.0' + libraryVersionCode = 200 + siteUrl = 'https://github.com/bestog/pals-lib' + gitUrl = 'https://github.com/bestog/pals-lib.git' + developerId = 'bestog' + developerName = 'Sebastian G.' + developerEmail = 'android@bestog.de' + licenseName = 'The Apache Software License, Version 2.0' + licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' + allLicenses = ["Apache-2.0"] +} + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.2" + + defaultConfig { + minSdkVersion 11 + targetSdkVersion 23 + versionCode libraryVersionCode + versionName libraryVersion + } + lintOptions { + abortOnError false + } +} + +apply from: '/../jcenter-install.gradle' +apply from: '/../jcenter-bintray.gradle' \ No newline at end of file diff --git a/pals/pals.iml b/pals/pals.iml new file mode 100644 index 0000000..e2ec451 --- /dev/null +++ b/pals/pals.iml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pals/proguard-rules.pro b/pals/proguard-rules.pro new file mode 100644 index 0000000..9af8911 --- /dev/null +++ b/pals/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:\Users\S.Gottschlich\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/main/java/com/bestog/pals/Pals.java b/pals/src/main/java/com/bestog/pals/Pals.java similarity index 79% rename from app/src/main/java/com/bestog/pals/Pals.java rename to pals/src/main/java/com/bestog/pals/Pals.java index 1791c09..f842170 100644 --- a/app/src/main/java/com/bestog/pals/Pals.java +++ b/pals/src/main/java/com/bestog/pals/Pals.java @@ -1,6 +1,7 @@ package com.bestog.pals; import android.content.Context; +import android.location.Location; import android.os.AsyncTask; import com.bestog.pals.interfaces.IRequest; @@ -11,11 +12,11 @@ import com.bestog.pals.provider.OpenBMapLocation; import com.bestog.pals.provider.OpenCellIDLocation; import com.bestog.pals.provider.OpenMapLocation; +import com.bestog.pals.utils.GPSPosition; import com.bestog.pals.utils.GeoResult; import com.bestog.pals.utils.Trilateration; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -25,17 +26,17 @@ * For more information: http://bestog.github.io/pals-lib * * @author bestog - * @version 1.0 */ public class Pals { private final Context context; private final Map enabledProviders = new HashMap<>(); - private final String trilaterateAlg = Trilateration.ALG_SIMPLE; - // Request + private String trilaterateAlg = Trilateration.ALG_SIMPLE; private final Map taskPool = new HashMap<>(); + // Request private final List resultList = new ArrayList<>(); - private final Collection submitList = new ArrayList<>(); - private int taskPoolCount = 0; + private int requestPoolCount = 0; + // Submit + private final List submitList = new ArrayList<>(); private int submitPoolCount = 0; // Listener private IRequest requestListener; @@ -84,6 +85,10 @@ public void enableProvider(String p) { } } + public String enabledProvider() { + return enabledProviders.toString(); + } + /** * Disable provider * @@ -114,7 +119,7 @@ public void request(IRequest listener) { this.requestListener = listener; for (LocationProvider lp : enabledProviders.values()) { taskPool.put(lp.getTitle(), new RequestATask().execute(lp)); - taskPoolCount++; + requestPoolCount++; } } @@ -124,12 +129,18 @@ public void request(IRequest listener) { * @param listener SubmitListener */ public void submit(ISubmit listener) { + GPSPosition gpsPosition = new GPSPosition(context); this.submitListener = listener; - for (LocationProvider lp : enabledProviders.values()) { - AsyncTask asyncTask = new SubmitATask().execute(lp); - taskPool.put(lp.getTitle(), asyncTask); - submitPoolCount++; - } + gpsPosition.getPosition(new GPSPosition.Listener() { + @Override + public void onComplete(Location geoResult, boolean valid) { + for (LocationProvider lp : enabledProviders.values()) { + AsyncTask asyncTask = new SubmitATask(geoResult).execute(lp); + taskPool.put(lp.getTitle(), asyncTask); + submitPoolCount++; + } + } + }); } /** @@ -139,7 +150,7 @@ public void submit(ISubmit listener) { * @param available valid geoResult? */ private void requestComplete(GeoResult geoResult, boolean available) { - --taskPoolCount; + --requestPoolCount; if (available) { GeoResult formatResult = new GeoResult(); formatResult.setLatitude(geoResult.getLatitude()); @@ -147,20 +158,31 @@ private void requestComplete(GeoResult geoResult, boolean available) { formatResult.setAccuracy(geoResult.getAccuracy()); resultList.add(formatResult); } - if (requestListener != null && taskPoolCount == 0) { + if (requestListener != null && requestPoolCount == 0) { GeoResult endResult = trilaterateResults(resultList); requestListener.onComplete(endResult, true); } } - private void submitComplete(String result, boolean valid) { + private void submitComplete(boolean success, boolean valid) { --submitPoolCount; - submitList.add(valid); + if (success) { + submitList.add(valid); + } if (submitListener != null && submitPoolCount == 0) { submitListener.onComplete(valid); } } + /** + * Set a trilaterate Algorithm + * + * @param alg string + */ + public void setTrilaterateAlg(String alg) { + trilaterateAlg = alg; + } + /** * Calculate all Points to an endresult * @@ -201,14 +223,20 @@ protected void onPostExecute(GeoResult geoResult) { */ private class SubmitATask extends AsyncTask { + private final Location gpsPosition; + + public SubmitATask(Location position) { + gpsPosition = position; + } + @Override protected Boolean doInBackground(LocationProvider... lp) { - return lp[0].submit(); + return lp[0].submit(gpsPosition); } @Override protected void onPostExecute(Boolean result) { - submitComplete("", true); + submitComplete(result, true); } } } diff --git a/app/src/main/java/com/bestog/pals/interfaces/IRequest.java b/pals/src/main/java/com/bestog/pals/interfaces/IRequest.java similarity index 100% rename from app/src/main/java/com/bestog/pals/interfaces/IRequest.java rename to pals/src/main/java/com/bestog/pals/interfaces/IRequest.java diff --git a/app/src/main/java/com/bestog/pals/interfaces/ISubmit.java b/pals/src/main/java/com/bestog/pals/interfaces/ISubmit.java similarity index 100% rename from app/src/main/java/com/bestog/pals/interfaces/ISubmit.java rename to pals/src/main/java/com/bestog/pals/interfaces/ISubmit.java diff --git a/app/src/main/java/com/bestog/pals/provider/GoogleLocation.java b/pals/src/main/java/com/bestog/pals/provider/GoogleLocation.java similarity index 95% rename from app/src/main/java/com/bestog/pals/provider/GoogleLocation.java rename to pals/src/main/java/com/bestog/pals/provider/GoogleLocation.java index 43d2776..1eb268c 100644 --- a/app/src/main/java/com/bestog/pals/provider/GoogleLocation.java +++ b/pals/src/main/java/com/bestog/pals/provider/GoogleLocation.java @@ -1,6 +1,7 @@ package com.bestog.pals.provider; import android.content.Context; +import android.location.Location; import com.bestog.pals.utils.CommonUtils; @@ -16,7 +17,6 @@ * Link: https://developers.google.com/maps/documentation/geolocation * * @author bestog - * @version 1.0 */ public class GoogleLocation extends LocationProvider { @@ -104,7 +104,7 @@ public String requestAction() { // @todo better logging e.printStackTrace(); } - return CommonUtils.getRequest(_requestUrl, request.toString(), "POST", "application/json;charset=utf-8"); + return CommonUtils.httpRequest(_requestUrl, request.toString(), "POST", "application/json;charset=utf-8"); } /** @@ -146,7 +146,7 @@ public boolean requestValidation(String response) { * @return String */ @Override - public String submitAction() { + public String submitAction(Location position) { return ""; } diff --git a/app/src/main/java/com/bestog/pals/provider/LocationProvider.java b/pals/src/main/java/com/bestog/pals/provider/LocationProvider.java similarity index 91% rename from app/src/main/java/com/bestog/pals/provider/LocationProvider.java rename to pals/src/main/java/com/bestog/pals/provider/LocationProvider.java index e1541fc..9178f57 100644 --- a/app/src/main/java/com/bestog/pals/provider/LocationProvider.java +++ b/pals/src/main/java/com/bestog/pals/provider/LocationProvider.java @@ -1,9 +1,9 @@ package com.bestog.pals.provider; import android.content.Context; +import android.location.Location; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; -import android.util.Log; import com.bestog.pals.utils.CellScanner; import com.bestog.pals.utils.GeoResult; @@ -16,7 +16,6 @@ * Class: Location Provider - abstract * * @author bestog - * @version 1.0 */ public abstract class LocationProvider { @@ -53,18 +52,18 @@ public void request() { } } - public boolean submit() { - String response = submitAction(); - return submitValidation(response); + public boolean submit(Location position) { + String response = submitAction(position); + return (submitValidation(response)); } protected abstract String requestAction(); - protected abstract void requestResult(String response); - protected abstract boolean requestValidation(String response); - protected abstract String submitAction(); + protected abstract void requestResult(String response); + + protected abstract String submitAction(Location position); protected abstract boolean submitValidation(String response); diff --git a/app/src/main/java/com/bestog/pals/provider/MozillaLocation.java b/pals/src/main/java/com/bestog/pals/provider/MozillaLocation.java similarity index 69% rename from app/src/main/java/com/bestog/pals/provider/MozillaLocation.java rename to pals/src/main/java/com/bestog/pals/provider/MozillaLocation.java index 684d530..ebf350e 100644 --- a/app/src/main/java/com/bestog/pals/provider/MozillaLocation.java +++ b/pals/src/main/java/com/bestog/pals/provider/MozillaLocation.java @@ -1,6 +1,8 @@ package com.bestog.pals.provider; import android.content.Context; +import android.location.Location; +import android.util.Log; import com.bestog.pals.utils.CommonUtils; @@ -8,6 +10,7 @@ import org.json.JSONException; import org.json.JSONObject; +import java.util.Calendar; import java.util.HashMap; import java.util.List; @@ -16,7 +19,6 @@ * Link: https://location.services.mozilla.com * * @author bestog - * @version 1.0 */ public class MozillaLocation extends LocationProvider { @@ -38,49 +40,6 @@ public MozillaLocation(Context ctx) { _submitApiUrl = _submitUrl + _submitToken; } - /** - * Convert a CellInfo in a specific format - * - * @param cell HashMap CellInfo - * @return JSONObject - */ - private static JSONObject convertCell(HashMap cell) { - JSONObject result = new JSONObject(); - try { - result.put("mobileCountryCode", Integer.parseInt(cell.get("mnc"))); - result.put("mobileNetworkCode", Integer.parseInt(cell.get("mcc"))); - result.put("locationAreaCode", Integer.parseInt(cell.get("lac"))); - result.put("cellId", Integer.parseInt(cell.get("cid"))); - if (cell.containsKey("dbm")) { - result.put("signalStrength", Integer.parseInt(cell.get("dbm"))); - } - } catch (JSONException e) { - // @todo better logging - e.printStackTrace(); - } - return result; - } - - /** - * Convert a WifiSpot in a specific format - * - * @param wifi HashMap Wifi - * @return JSONObject - */ - private static JSONObject convertWifi(HashMap wifi) { - JSONObject result = new JSONObject(); - try { - result.put("macAddress", wifi.get("key")); - result.put("channel", Integer.parseInt(wifi.get("channel"))); - result.put("frequency", Integer.parseInt(wifi.get("frequency"))); - result.put("signalStrength", Integer.parseInt(wifi.get("signal"))); - } catch (JSONException e) { - // @todo better logging - e.printStackTrace(); - } - return result; - } - /** * request Action * @@ -108,7 +67,7 @@ public String requestAction() { // @todo better logging e.printStackTrace(); } - return CommonUtils.getRequest(_requestApiUrl, request.toString(), "POST", "application/json;charset=utf-8"); + return CommonUtils.httpRequest(_requestApiUrl, request.toString(), "POST", "application/json;charset=utf-8"); } /** @@ -152,8 +111,34 @@ protected boolean requestValidation(String response) { * @return String */ @Override - public String submitAction() { - return ""; + public String submitAction(Location position) { + JSONObject reports = new JSONObject(); + JSONObject report = new JSONObject(); + List> cellTowers = getCellTowers(); + List> wifiSpots = getWifiSpots(); + try { + JSONArray cellArray = new JSONArray(); + for (HashMap cell : cellTowers) { + if (!cell.get("cid").equals(LocationProvider.UNKNOWN_CELLID)) { + cellArray.put(convertCell(cell)); + } + } + report.put("cellTowers", cellArray); + JSONArray wifiArray = new JSONArray(); + for (HashMap wifi : wifiSpots) { + wifiArray.put(convertWifi(wifi)); + } + report.put("wifiAccessPoints", wifiArray); + report.put("timestamp", (new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())).getTime()); + report.put("position", convertPosition(position)); + JSONArray jsonArray = new JSONArray(); + jsonArray.put(report); + reports.put("items", jsonArray); + } catch (JSONException e) { + // @todo better logging + e.printStackTrace(); + } + return CommonUtils.httpRequest(_submitApiUrl, reports.toString(), "POST", "application/json;charset=utf-8"); } /** @@ -164,6 +149,64 @@ public String submitAction() { */ @Override public boolean submitValidation(String response) { - return true; + return response.isEmpty(); + } + + /** + * Convert a CellInfo in a specific format + * + * @param cell HashMap CellInfo + * @return JSONObject + */ + private static JSONObject convertCell(HashMap cell) { + JSONObject result = new JSONObject(); + try { + result.put("mobileCountryCode", Integer.parseInt(cell.get("mnc"))); + result.put("mobileNetworkCode", Integer.parseInt(cell.get("mcc"))); + result.put("locationAreaCode", Integer.parseInt(cell.get("lac"))); + result.put("cellId", Integer.parseInt(cell.get("cid"))); + if (cell.containsKey("dbm")) { + result.put("signalStrength", Integer.parseInt(cell.get("dbm"))); + } + } catch (JSONException e) { + // @todo better logging + e.printStackTrace(); + } + return result; + } + + /** + * Convert a WifiSpot in a specific format + * + * @param wifi HashMap Wifi + * @return JSONObject + */ + private static JSONObject convertWifi(HashMap wifi) { + JSONObject result = new JSONObject(); + try { + result.put("macAddress", wifi.get("key")); + result.put("channel", Integer.parseInt(wifi.get("channel"))); + result.put("frequency", Integer.parseInt(wifi.get("frequency"))); + result.put("signalStrength", Integer.parseInt(wifi.get("signal"))); + } catch (JSONException e) { + // @todo better logging + e.printStackTrace(); + } + return result; + } + + private static JSONObject convertPosition(Location position) { + JSONObject result = new JSONObject(); + try { + result.put("latitude", position.getLatitude()); + result.put("longitude", position.getLongitude()); + result.put("accuracy", position.getAccuracy()); + result.put("altitude", position.getAltitude()); + result.put("speed", position.getSpeed()); + result.put("source", "gps"); + } catch (JSONException e) { + e.printStackTrace(); + } + return result; } } diff --git a/app/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java b/pals/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java similarity index 94% rename from app/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java rename to pals/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java index fce0c09..ca14ede 100644 --- a/app/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java +++ b/pals/src/main/java/com/bestog/pals/provider/OpenBMapLocation.java @@ -1,9 +1,10 @@ package com.bestog.pals.provider; import android.content.Context; -import android.util.Log; +import android.location.Location; import com.bestog.pals.utils.CommonUtils; +import com.bestog.pals.utils.GeoResult; import org.json.JSONArray; import org.json.JSONException; @@ -17,7 +18,6 @@ * Link: http://www.radiocells.org * * @author bestog - * @version 1.0 */ public class OpenBMapLocation extends LocationProvider { @@ -99,7 +99,7 @@ public String requestAction() { // @todo better logging e.printStackTrace(); } - return CommonUtils.getRequest(_requestUrl, request.toString(), "POST", "application/json;charset=utf-8"); + return CommonUtils.httpRequest(_requestUrl, request.toString(), "POST", "application/json;charset=utf-8"); } /** @@ -144,7 +144,7 @@ public boolean requestValidation(String response) { * @return String */ @Override - public String submitAction() { + public String submitAction(Location position) { return ""; } diff --git a/app/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java b/pals/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java similarity index 93% rename from app/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java rename to pals/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java index 7b179af..6cc37c9 100644 --- a/app/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java +++ b/pals/src/main/java/com/bestog/pals/provider/OpenCellIDLocation.java @@ -2,8 +2,10 @@ import android.content.Context; +import android.location.Location; import com.bestog.pals.utils.CommonUtils; +import com.bestog.pals.utils.GeoResult; import org.json.JSONException; import org.json.JSONObject; @@ -18,7 +20,6 @@ * Link: http://opencellid.org * * @author bestog - * @version 1.0 */ public class OpenCellIDLocation extends LocationProvider { @@ -50,7 +51,7 @@ public String requestAction() { String url = _requestUrl + "&mcc=" + cellInfo.get("mnc") + "&mnc=" + cellInfo .get("mcc") + "&cellid=" + cellInfo.get("cid") + "&lac=" + cellInfo .get("lac") + "&format=json"; - String response = CommonUtils.getRequest(url, "", "GET", "application/json;charset=utf-8"); + String response = CommonUtils.httpRequest(url, "", "GET", "application/json;charset=utf-8"); boolean status = requestValidation(response); if (status) { try { @@ -115,7 +116,7 @@ protected boolean requestValidation(String response) { * @return String */ @Override - public String submitAction() { + public String submitAction(Location position) { return ""; } diff --git a/app/src/main/java/com/bestog/pals/provider/OpenMapLocation.java b/pals/src/main/java/com/bestog/pals/provider/OpenMapLocation.java similarity index 90% rename from app/src/main/java/com/bestog/pals/provider/OpenMapLocation.java rename to pals/src/main/java/com/bestog/pals/provider/OpenMapLocation.java index 0a4e0e3..245dbce 100644 --- a/app/src/main/java/com/bestog/pals/provider/OpenMapLocation.java +++ b/pals/src/main/java/com/bestog/pals/provider/OpenMapLocation.java @@ -1,8 +1,10 @@ package com.bestog.pals.provider; import android.content.Context; +import android.location.Location; import com.bestog.pals.utils.CommonUtils; +import com.bestog.pals.utils.GeoResult; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -15,7 +17,6 @@ * Link: https://openwifi.su * * @author bestog - * @version 1.0 */ public class OpenMapLocation extends LocationProvider { @@ -45,7 +46,7 @@ public String requestAction() { for (HashMap wifi : wifiSpots) { request += wifi.get("key") + "\r\n"; } - return CommonUtils.getRequest(_requestUrl, request, "POST", "application/x-www-form-urlencoded, *.*"); + return CommonUtils.httpRequest(_requestUrl, request, "POST", "application/x-www-form-urlencoded, *.*"); } /** @@ -86,7 +87,7 @@ public boolean requestValidation(String response) { * @return String */ @Override - public String submitAction() { + public String submitAction(Location position) { return ""; } diff --git a/app/src/main/java/com/bestog/pals/utils/CellScanner.java b/pals/src/main/java/com/bestog/pals/utils/CellScanner.java similarity index 79% rename from app/src/main/java/com/bestog/pals/utils/CellScanner.java rename to pals/src/main/java/com/bestog/pals/utils/CellScanner.java index c5ca43a..21e270c 100644 --- a/app/src/main/java/com/bestog/pals/utils/CellScanner.java +++ b/pals/src/main/java/com/bestog/pals/utils/CellScanner.java @@ -80,7 +80,7 @@ private static String getTypeAsString(int type) { */ public List> getCells() { List> result = new ArrayList<>(); - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { List cellInfos = telephonyManager.getAllCellInfo(); for (CellInfo item : cellInfos) { HashMap cell = new HashMap<>(); @@ -98,17 +98,19 @@ public List> getCells() { result.add(cell); } } - List cellInfoList = telephonyManager.getNeighboringCellInfo(); - String networkOperator = telephonyManager.getNetworkOperator(); - for (NeighboringCellInfo cellInfo : cellInfoList) { - HashMap cell = new HashMap<>(); - cell.put("lac", String.valueOf(cellInfo.getLac())); - cell.put("cid", String.valueOf(cellInfo.getCid())); - cell.put("mcc", networkOperator.substring(3)); - cell.put("mnc", networkOperator.substring(0, 3)); - cell.put("dbm", String.valueOf(-1 * 113 + 2 * cellInfo.getRssi())); - cell.put("radio", getTypeAsString(cellInfo.getNetworkType())); - result.add(cell); + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) { + List cellInfoList = telephonyManager.getNeighboringCellInfo(); + String networkOperator = telephonyManager.getNetworkOperator(); + for (NeighboringCellInfo cellInfo : cellInfoList) { + HashMap cell = new HashMap<>(); + cell.put("lac", String.valueOf(cellInfo.getLac())); + cell.put("cid", String.valueOf(cellInfo.getCid())); + cell.put("mcc", networkOperator.substring(3)); + cell.put("mnc", networkOperator.substring(0, 3)); + cell.put("dbm", String.valueOf(-1 * 113 + 2 * cellInfo.getRssi())); + cell.put("radio", getTypeAsString(cellInfo.getNetworkType())); + result.add(cell); + } } return result; } diff --git a/app/src/main/java/com/bestog/pals/utils/CommonUtils.java b/pals/src/main/java/com/bestog/pals/utils/CommonUtils.java similarity index 78% rename from app/src/main/java/com/bestog/pals/utils/CommonUtils.java rename to pals/src/main/java/com/bestog/pals/utils/CommonUtils.java index 8c085c6..1298ce4 100644 --- a/app/src/main/java/com/bestog/pals/utils/CommonUtils.java +++ b/pals/src/main/java/com/bestog/pals/utils/CommonUtils.java @@ -13,7 +13,7 @@ /** * Class: CommonUtils - * Important features for the library + * Important functions for the library * * @author bestog */ @@ -28,7 +28,7 @@ public final class CommonUtils { * @param contentType Content-Type * @return String */ - public static String getRequest(String url, String body, String httpMethod, String contentType) { + public static String httpRequest(String url, String body, String httpMethod, String contentType) { InputStream inputStream = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); @@ -73,21 +73,20 @@ public static double round(double value, int places) { * @return string */ private static String streamToString(InputStream stream) { - if (stream == null) { - return ""; - } StringWriter writer = null; - try { - InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); - writer = new StringWriter(); - int n; - char[] buffer = new char[1024 * 4]; - while (-1 != (n = reader.read(buffer))) { - writer.write(buffer, 0, n); + if (stream != null) { + try { + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + writer = new StringWriter(); + int n; + char[] buffer = new char[1024 * 4]; + while (-1 != (n = reader.read(buffer))) { + writer.write(buffer, 0, n); + } + } catch (IOException e) { + // @todo better logging + e.printStackTrace(); } - } catch (IOException e) { - // @todo better logging - e.printStackTrace(); } return writer != null ? writer.toString() : ""; } diff --git a/pals/src/main/java/com/bestog/pals/utils/GPSPosition.java b/pals/src/main/java/com/bestog/pals/utils/GPSPosition.java new file mode 100644 index 0000000..00a092b --- /dev/null +++ b/pals/src/main/java/com/bestog/pals/utils/GPSPosition.java @@ -0,0 +1,119 @@ +package com.bestog.pals.utils; + +import android.content.Context; +import android.location.Criteria; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Bundle; + +import java.util.Calendar; + +/** + * Class: GPSPosition + * + * @author bestog + */ +public class GPSPosition { + /** + * Variables + */ + private final Context ctx; + private Listener listener; + + /** + * constructor + * + * @param context Activity + */ + public GPSPosition(Context context) { + ctx = context; + } + + /** + * Get coordinates + * + * @param listener Listener + */ + public final void getPosition(Listener listener) { + this.listener = listener; + this.getFromGps(); + } + + /** + * Get coordinates from GPS system + */ + private void getFromGps() { + final LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE); + Location location = null; + if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + try { + location = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), true)); + } catch (SecurityException e) { + //@todo: better logging + complete(location, false); + e.printStackTrace(); + } + if (location != null + && location.getTime() > Calendar.getInstance().getTimeInMillis() - (long) (2 * 60 + * 1000)) { + double lat = CommonUtils.round(location.getLatitude(), 6); + double lon = CommonUtils.round(location.getLongitude(), 6); + complete(location, lat != 0 && lon != 0); + } else { + try { + locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, + new LocationListener() { + @Override + public void onLocationChanged(Location location) { + if (location != null) { + getFromGps(); + try { + locationManager.removeUpdates(this); + } catch (SecurityException e) { + e.printStackTrace(); + // @todo better logging + } + } + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + } + + @Override + public void onProviderEnabled(String provider) { + } + + @Override + public void onProviderDisabled(String provider) { + } + }); + } catch (SecurityException e) { + complete(location, false); + e.printStackTrace(); + } + } + } + } + + /** + * if complete + * + * @param geoResult Location + * @param available valid coordinates? + */ + private void complete(Location geoResult, boolean available) { + if (this.listener != null) { + this.listener.onComplete(geoResult, available); + } + } + + /** + * Interface Listener + */ + public interface Listener { + void onComplete(Location geoResult, boolean valid); + } +} + diff --git a/app/src/main/java/com/bestog/pals/utils/GeoResult.java b/pals/src/main/java/com/bestog/pals/utils/GeoResult.java similarity index 98% rename from app/src/main/java/com/bestog/pals/utils/GeoResult.java rename to pals/src/main/java/com/bestog/pals/utils/GeoResult.java index 1ecd180..9063047 100644 --- a/app/src/main/java/com/bestog/pals/utils/GeoResult.java +++ b/pals/src/main/java/com/bestog/pals/utils/GeoResult.java @@ -4,7 +4,6 @@ * Class: GeoResult * * @author bestog - * @version 1.0 */ public class GeoResult { diff --git a/app/src/main/java/com/bestog/pals/utils/Trilateration.java b/pals/src/main/java/com/bestog/pals/utils/Trilateration.java similarity index 96% rename from app/src/main/java/com/bestog/pals/utils/Trilateration.java rename to pals/src/main/java/com/bestog/pals/utils/Trilateration.java index fb9ecd4..9a8ddd9 100644 --- a/app/src/main/java/com/bestog/pals/utils/Trilateration.java +++ b/pals/src/main/java/com/bestog/pals/utils/Trilateration.java @@ -12,7 +12,7 @@ public final class Trilateration { /** * All coordinates are added together and it creates the final result (rudimentarily) - * http://www.geomidpoint.com/calculation.html > Point A + * http://www.geomidpoint.com/calculation.html = Point A * * @param resultList locations * @return GeoResult diff --git a/app/src/main/java/com/bestog/pals/utils/WifiScanner.java b/pals/src/main/java/com/bestog/pals/utils/WifiScanner.java similarity index 100% rename from app/src/main/java/com/bestog/pals/utils/WifiScanner.java rename to pals/src/main/java/com/bestog/pals/utils/WifiScanner.java diff --git a/pals/src/main/res/values/strings.xml b/pals/src/main/res/values/strings.xml new file mode 100644 index 0000000..06a51ca --- /dev/null +++ b/pals/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Pals + diff --git a/settings.gradle b/settings.gradle index e7b4def..a5257f9 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,2 @@ +include ':pals' include ':app'