This commit is contained in:
Dennis Thießen
2017-06-10 12:04:00 +02:00
parent b79b5d7f3f
commit 8f94b075c2
14 changed files with 425 additions and 349 deletions

2
.idea/misc.xml generated
View File

@@ -37,7 +37,7 @@
<ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" /> <ConfirmationsSetting value="0" id="Remove" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="JDK" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">

View File

@@ -13,7 +13,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" /> <excludeFolder url="file://$MODULE_DIR$/.gradle" />
</content> </content>
<orderEntry type="jdk" jdkName="JDK" jdkType="JavaSDK" /> <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>

View File

@@ -92,6 +92,7 @@
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard-rules" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/reload-dex" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/reload-dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/restart-dex" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/restart-dex" />
@@ -101,6 +102,7 @@
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" /> <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/reports" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" /> <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content> </content>
<orderEntry type="jdk" jdkName="Android API 25 Platform" jdkType="Android SDK" /> <orderEntry type="jdk" jdkName="Android API 25 Platform" jdkType="Android SDK" />
@@ -145,6 +147,5 @@
<orderEntry type="library" exported="" name="support-compat-25.3.1" level="project" /> <orderEntry type="library" exported="" name="support-compat-25.3.1" level="project" />
<orderEntry type="library" exported="" name="animated-vector-drawable-25.3.1" level="project" /> <orderEntry type="library" exported="" name="animated-vector-drawable-25.3.1" level="project" />
<orderEntry type="library" exported="" name="iconics-core-2.8.2" level="project" /> <orderEntry type="library" exported="" name="iconics-core-2.8.2" level="project" />
<orderEntry type="library" exported="" name="android-android-25" level="project" />
</component> </component>
</module> </module>

View File

@@ -13,14 +13,14 @@ apply plugin: 'com.google.gms.google-services'
android { android {
compileSdkVersion 25 compileSdkVersion 25
buildToolsVersion '25.0.0' buildToolsVersion '25.0.2'
defaultConfig { defaultConfig {
applicationId "org.deke.risk.riskahead" applicationId "org.deke.risk.riskahead"
minSdkVersion 15 minSdkVersion 15
targetSdkVersion 23 targetSdkVersion 23
versionCode 35 versionCode 42
versionName "2.1.1" versionName "3.0.2"
} }
buildTypes { buildTypes {
release { release {

View File

@@ -22,7 +22,6 @@ import android.util.Patterns;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton; import android.widget.CompoundButton;
import android.widget.LinearLayout; import android.widget.LinearLayout;
@@ -45,8 +44,6 @@ import com.android.volley.Response;
import com.android.volley.VolleyError; import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.StringRequest;
import com.beardedhen.androidbootstrap.BootstrapButton; import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -314,9 +311,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr
@Override @Override
protected Map<String, String> getParams() { protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>(); return new HashMap<>();
return params;
} }
}; };
} }

View File

@@ -31,6 +31,7 @@ import android.widget.TextView;
import com.android.volley.Request; import com.android.volley.Request;
import com.android.volley.Response; import com.android.volley.Response;
import com.android.volley.VolleyError; import com.android.volley.VolleyError;
import android.location.LocationListener; import android.location.LocationListener;
import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.StringRequest;
@@ -70,11 +71,9 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
*
* (C) Copyright 2016 RiskAhead (http://www.riskahead.net) * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
* Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
* Date of Release: 10.02.2016 * Date of Release: 10.02.2016
*
*/ */
public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>, public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>,
ClusterManager.OnClusterItemInfoWindowClickListener<IncidentReport>, ClusterManager.OnClusterClickListener<IncidentReport>, ClusterManager.OnClusterItemClickListener<IncidentReport>, OnMapReadyCallback { ClusterManager.OnClusterItemInfoWindowClickListener<IncidentReport>, ClusterManager.OnClusterClickListener<IncidentReport>, ClusterManager.OnClusterItemClickListener<IncidentReport>, OnMapReadyCallback {
@@ -101,8 +100,10 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
private Marker markerShowingInfoWindow; private Marker markerShowingInfoWindow;
private IncidentReport clickedClusterItem; private IncidentReport clickedClusterItem;
protected LocationManager locationManager; private LocationManager locationManager;
Location location; private LocationListener locationListener;
private Location location;
private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
@@ -121,6 +122,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
userHasToBeLoggedIn(); userHasToBeLoggedIn();
if (session.getSubsPremium()) { if (session.getSubsPremium()) {
MIN_ZOOM_LEVEL = 7; MIN_ZOOM_LEVEL = 7;
} else { } else {
@@ -138,6 +140,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
public void onMapReady(GoogleMap googleMap) { public void onMapReady(GoogleMap googleMap) {
mMap = googleMap; mMap = googleMap;
initMap(); initMap();
handleIntent(getIntent()); handleIntent(getIntent());
initClustering(); initClustering();
} }
@@ -150,21 +153,16 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
@Override @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d(TAG,"Getting permission results..."); Log.d(TAG, "Getting permission results...");
switch (requestCode) { switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: { case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission was granted by user"); Log.d(TAG, "Permission was granted by user");
enableMyLocationButton();
try{
mMap.setMyLocationEnabled(true);
}catch (SecurityException e){
Log.e(TAG,"Security Exception:"+e.getMessage());
}
getLocation(); getLocation();
}else{
Log.d(TAG,"Permission was not granted by user"); } else {
Log.d(TAG, "Permission was not granted by user");
String sDefSystemLanguage = Locale.getDefault().getLanguage(); String sDefSystemLanguage = Locale.getDefault().getLanguage();
@@ -182,29 +180,25 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
new LatLng(19.410704, -99.132385), DEFAULT_ZOOM_LEVEL)); new LatLng(19.410704, -99.132385), DEFAULT_ZOOM_LEVEL));
break; break;
} }
try{
mMap.setMyLocationEnabled(false);
}catch (SecurityException e){
Log.e(TAG,"Security Exception:"+e.getMessage());
}
} }
} }
} }
} }
private void initMap() { private void initMap() {
Log.d(TAG,"Init Map"); Log.d(TAG, "Init Map");
mMap.getUiSettings().setZoomControlsEnabled(true); mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMinZoomPreference(MIN_ZOOM_LEVEL);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override @Override
public boolean onMyLocationButtonClick() { public boolean onMyLocationButtonClick() {
getLocation(); getLocation();
return true; return false;
} }
}); });
enableMyLocationButton();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override @Override
public void onMapClick(LatLng point) { public void onMapClick(LatLng point) {
@@ -254,13 +248,13 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
addButton.setOnClickListener(new View.OnClickListener() { addButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
session.setLocation(Double.doubleToRawLongBits(markedLocation.latitude), Double.doubleToRawLongBits(markedLocation.longitude)); session.setManualLocation(Double.doubleToRawLongBits(markedLocation.latitude), Double.doubleToRawLongBits(markedLocation.longitude));
Log.d(TAG, "MARKED LOCATION: " + markedLocation.latitude + " " + markedLocation.longitude); Log.d(TAG, "MARKED LOCATION: " + markedLocation.latitude + " " + markedLocation.longitude);
gotoSettingsActivity(); gotoSettingsActivity();
} }
}); });
} }
}else{ } else {
addButton.setOnClickListener(new View.OnClickListener() { addButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@@ -276,31 +270,22 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
public GoogleMap.OnCameraIdleListener getCameraChangeListener() { public GoogleMap.OnCameraIdleListener getCameraChangeListener() {
return new GoogleMap.OnCameraIdleListener() return new GoogleMap.OnCameraIdleListener() {
{
@Override @Override
public void onCameraIdle() public void onCameraIdle() {
{
mClusterManager.onCameraIdle(); mClusterManager.onCameraIdle();
CameraPosition position = mMap.getCameraPosition(); CameraPosition position = mMap.getCameraPosition();
if((position.zoom < MIN_ZOOM_LEVEL) && !session.getSubsPremium()) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(MIN_ZOOM_LEVEL));
showMessage(getString(R.string.txt_map_zoomoutpremium));
return;
}
current_zoom_level = position.zoom; current_zoom_level = position.zoom;
if(position.zoom > 13) { if (position.zoom > 13) {
PRELOAD_PERCENTAGE = 0.7; PRELOAD_PERCENTAGE = 0.7;
}else{ } else {
PRELOAD_PERCENTAGE = 0.3; PRELOAD_PERCENTAGE = 0.3;
} }
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
Log.d("OnCameraChangeListener", "Position: "+bounds.getCenter()+" Zoom: "+position.zoom + " Bounds: NE:" + bounds.northeast + " SW: " + bounds.southwest); Log.d("OnCameraChangeListener", "Position: " + bounds.getCenter() + " Zoom: " + position.zoom + " Bounds: NE:" + bounds.northeast + " SW: " + bounds.southwest);
Log.d("OnCameraChangeListener", "Saved Position - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds); Log.d("OnCameraChangeListener", "Saved Position - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds);
boolean isOutOfBounds = false; boolean isOutOfBounds = false;
@@ -311,39 +296,39 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
double southwestLat, southwestLng; double southwestLat, southwestLng;
double northeastLat, northeastLng; double northeastLat, northeastLng;
if(bounds.southwest.latitude < bounds.northeast.latitude){ if (bounds.southwest.latitude < bounds.northeast.latitude) {
southwestLat = bounds.southwest.latitude - distanceLat * PRELOAD_PERCENTAGE; southwestLat = bounds.southwest.latitude - distanceLat * PRELOAD_PERCENTAGE;
northeastLat = bounds.northeast.latitude + distanceLat * PRELOAD_PERCENTAGE; northeastLat = bounds.northeast.latitude + distanceLat * PRELOAD_PERCENTAGE;
if((curSouthwestBounds != null) && ((bounds.southwest.latitude < curSouthwestBounds.latitude) || (bounds.northeast.latitude > curNortheastBounds.latitude))){ if ((curSouthwestBounds != null) && ((bounds.southwest.latitude < curSouthwestBounds.latitude) || (bounds.northeast.latitude > curNortheastBounds.latitude))) {
isOutOfBounds = true; isOutOfBounds = true;
} }
} else { } else {
southwestLat = bounds.southwest.latitude + distanceLat * PRELOAD_PERCENTAGE; southwestLat = bounds.southwest.latitude + distanceLat * PRELOAD_PERCENTAGE;
northeastLat = bounds.northeast.latitude - distanceLat * PRELOAD_PERCENTAGE; northeastLat = bounds.northeast.latitude - distanceLat * PRELOAD_PERCENTAGE;
if((curSouthwestBounds != null) && ((bounds.southwest.latitude > curSouthwestBounds.latitude) || (bounds.northeast.latitude < curNortheastBounds.latitude))){ if ((curSouthwestBounds != null) && ((bounds.southwest.latitude > curSouthwestBounds.latitude) || (bounds.northeast.latitude < curNortheastBounds.latitude))) {
isOutOfBounds = true; isOutOfBounds = true;
} }
} }
if(bounds.southwest.longitude < bounds.northeast.longitude){ if (bounds.southwest.longitude < bounds.northeast.longitude) {
southwestLng = bounds.southwest.longitude - distanceLon * PRELOAD_PERCENTAGE; southwestLng = bounds.southwest.longitude - distanceLon * PRELOAD_PERCENTAGE;
northeastLng = bounds.northeast.longitude + distanceLon * PRELOAD_PERCENTAGE; northeastLng = bounds.northeast.longitude + distanceLon * PRELOAD_PERCENTAGE;
if((curSouthwestBounds != null) && ((bounds.southwest.longitude < curSouthwestBounds.longitude) || (bounds.northeast.longitude > curNortheastBounds.longitude))){ if ((curSouthwestBounds != null) && ((bounds.southwest.longitude < curSouthwestBounds.longitude) || (bounds.northeast.longitude > curNortheastBounds.longitude))) {
isOutOfBounds = true; isOutOfBounds = true;
} }
} else { } else {
southwestLng = bounds.southwest.longitude + distanceLon * PRELOAD_PERCENTAGE; southwestLng = bounds.southwest.longitude + distanceLon * PRELOAD_PERCENTAGE;
northeastLng = bounds.northeast.longitude - distanceLon * PRELOAD_PERCENTAGE; northeastLng = bounds.northeast.longitude - distanceLon * PRELOAD_PERCENTAGE;
if((curSouthwestBounds != null) && ((bounds.southwest.longitude > curSouthwestBounds.longitude) || (bounds.northeast.longitude < curNortheastBounds.longitude))){ if ((curSouthwestBounds != null) && ((bounds.southwest.longitude > curSouthwestBounds.longitude) || (bounds.northeast.longitude < curNortheastBounds.longitude))) {
isOutOfBounds = true; isOutOfBounds = true;
} }
} }
if((curSouthwestBounds == null) || isOutOfBounds) { if ((curSouthwestBounds == null) || isOutOfBounds) {
curNortheastBounds = new LatLng(northeastLat, northeastLng); curNortheastBounds = new LatLng(northeastLat, northeastLng);
curSouthwestBounds = new LatLng(southwestLat, southwestLng); curSouthwestBounds = new LatLng(southwestLat, southwestLng);
@@ -358,7 +343,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds);
markersShown = false; markersShown = false;
} }
} else if((position.zoom >= THRESHOLD_ZOOM_LEVEL) && !markersShown){ } else if ((position.zoom >= THRESHOLD_ZOOM_LEVEL) && !markersShown) {
curNortheastBounds = new LatLng(northeastLat, northeastLng); curNortheastBounds = new LatLng(northeastLat, northeastLng);
curSouthwestBounds = new LatLng(southwestLat, southwestLng); curSouthwestBounds = new LatLng(southwestLat, southwestLng);
@@ -367,7 +352,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds);
refreshIncidentMarkers(curNortheastBounds, curSouthwestBounds); refreshIncidentMarkers(curNortheastBounds, curSouthwestBounds);
markersShown = true; markersShown = true;
} else if((position.zoom < THRESHOLD_ZOOM_LEVEL) && !markersShown){ } else if ((position.zoom < THRESHOLD_ZOOM_LEVEL) && !markersShown) {
mClusterManager.clearItems(); mClusterManager.clearItems();
markersShown = false; markersShown = false;
} }
@@ -375,19 +360,18 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
}; };
} }
private void refreshIncidentMarkers(LatLng northeast, LatLng southwest){ private void refreshIncidentMarkers(LatLng northeast, LatLng southwest) {
showProgress(); showProgress();
String tag_string_req = "getincidentsfrombound"; String tag_string_req = "getincidentsfrombound";
StringRequest strReq = getStringRequestGetAllIncidentsFromBound(northeast,southwest); StringRequest strReq = getStringRequestGetAllIncidentsFromBound(northeast, southwest);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req); AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
} }
private void addIncidentMarkersOnMap(JSONArray incidents){ private void addIncidentMarkersOnMap(JSONArray incidents) {
mClusterManager.clearItems(); mClusterManager.clearItems();
for(int i = 0; i < incidents.length();i++){ for (int i = 0; i < incidents.length(); i++) {
try { try {
mClusterManager.addItem(new IncidentReport(incidents.getJSONObject(i))); mClusterManager.addItem(new IncidentReport(incidents.getJSONObject(i)));
} catch (JSONException e) { } catch (JSONException e) {
@@ -398,7 +382,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
mClusterManager.cluster(); mClusterManager.cluster();
} }
private void refreshIncidentHeatMap(LatLng northeast, LatLng southwest){ private void refreshIncidentHeatMap(LatLng northeast, LatLng southwest) {
showProgress(); showProgress();
String tag_string_req = "getincidentsforheatmapfrombound"; String tag_string_req = "getincidentsforheatmapfrombound";
@@ -406,10 +390,10 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
AppController.getInstance().addToRequestQueue(strReq, tag_string_req); AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
} }
private void addIncidentMarkersOnHeatMap(JSONArray incidents){ private void addIncidentMarkersOnHeatMap(JSONArray incidents) {
ArrayList<WeightedLatLng> heatMapPositions = new ArrayList<>(); ArrayList<WeightedLatLng> heatMapPositions = new ArrayList<>();
for(int i = 0; i < incidents.length();i++){ for (int i = 0; i < incidents.length(); i++) {
try { try {
heatMapPositions.add(new WeightedLatLng(new LatLng(incidents.getJSONObject(i).getDouble("latitude"), incidents.getJSONObject(i).getDouble("longitude")), 1.0)); heatMapPositions.add(new WeightedLatLng(new LatLng(incidents.getJSONObject(i).getDouble("latitude"), incidents.getJSONObject(i).getDouble("longitude")), 1.0));
} catch (JSONException e) { } catch (JSONException e) {
@@ -417,20 +401,17 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
} }
if(mProvider == null){ if (mProvider == null) {
mProvider = new HeatmapTileProvider.Builder() mProvider = new HeatmapTileProvider.Builder()
.radius(50) .radius(50)
.weightedData(heatMapPositions) .weightedData(heatMapPositions)
.opacity(0.7) .opacity(0.7)
.build(); .build();
mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider)); mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
Log.d("HEATMAP", "HeatMap initialized"); } else {
}else{
mProvider.setWeightedData(heatMapPositions); mProvider.setWeightedData(heatMapPositions);
mOverlay.clearTileCache(); mOverlay.clearTileCache();
Log.d("HEATMAP", "HeatMap updated");
} }
} }
@@ -447,7 +428,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
if (!error) { if (!error) {
JSONArray incidents = jObj.getJSONArray("msg"); JSONArray incidents = jObj.getJSONArray("msg");
Log.d(TAG, "HeatMap positions response length: " + incidents .length()); Log.d(TAG, "HeatMap positions response length: " + incidents.length());
addIncidentMarkersOnHeatMap(incidents); addIncidentMarkersOnHeatMap(incidents);
} else { } else {
String errorMsg = jObj.getString("error_msg"); String errorMsg = jObj.getString("error_msg");
@@ -554,7 +535,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
new MyCustomAdapterForItems()); new MyCustomAdapterForItems());
} }
private void loadInfoWindowInformation(View infoView, String incidentID){ private void loadInfoWindowInformation(View infoView, String incidentID) {
showProgress(); showProgress();
String tag_string_req = "getincidentscoreforinfowindow"; String tag_string_req = "getincidentscoreforinfowindow";
@@ -580,7 +561,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
TextView tvUsername = ((TextView) infoView.findViewById(R.id.txt_infowindow_fromuser)); TextView tvUsername = ((TextView) infoView.findViewById(R.id.txt_infowindow_fromuser));
RatingBar rbScore = ((RatingBar) infoView.findViewById(R.id.rb_infowindow_rating)); RatingBar rbScore = ((RatingBar) infoView.findViewById(R.id.rb_infowindow_rating));
tvUsername.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_author),clickedClusterItem.getFromUsername())); tvUsername.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_author), clickedClusterItem.getFromUsername()));
rbScore.setRating(clickedClusterItem.getScoreStars()); rbScore.setRating(clickedClusterItem.getScoreStars());
if (markerShowingInfoWindow != null && markerShowingInfoWindow.isInfoWindowShown()) { if (markerShowingInfoWindow != null && markerShowingInfoWindow.isInfoWindowShown()) {
@@ -589,7 +570,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
} else { } else {
String errorMsg = jObj.getString("error_msg"); String errorMsg = jObj.getString("error_msg");
Log.e(TAG, "Error getting incident details (server returned error): " + errorMsg); Log.i(TAG, "Error getting incident details (server returned error): " + errorMsg);
showMessage(getResources().getString(R.string.txt_errormsg_getinfowindow)); showMessage(getResources().getString(R.string.txt_errormsg_getinfowindow));
} }
} catch (JSONException e) { } catch (JSONException e) {
@@ -617,9 +598,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
}; };
} }
private class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter { private class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter {
private final View myContentsView; private final View myContentsView;
MyCustomAdapterForItems() { MyCustomAdapterForItems() {
@@ -652,40 +631,39 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
tvCategory.setText(clickedClusterItem.getIncidentCategoryName(getApplicationContext())); tvCategory.setText(clickedClusterItem.getIncidentCategoryName(getApplicationContext()));
tvSubcategory.setText(clickedClusterItem.getIncidentSubCategoryName(getApplicationContext())); tvSubcategory.setText(clickedClusterItem.getIncidentSubCategoryName(getApplicationContext()));
tvSuspect.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_suspect),clickedClusterItem.getSuspectString(getApplicationContext()))); tvSuspect.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_suspect), clickedClusterItem.getSuspectString(getApplicationContext())));
tvVictim.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_victim),clickedClusterItem.getVictimString(getApplicationContext()))); tvVictim.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_victim), clickedClusterItem.getVictimString(getApplicationContext())));
tvTime.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_time), clickedClusterItem.getTimeString(getApplicationContext()))); tvTime.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_time), clickedClusterItem.getTimeString(getApplicationContext())));
} }
return myContentsView; return myContentsView;
} }
} }
private void handleIntent(Intent intent){ private void handleIntent(Intent intent) {
if(Intent.ACTION_SEARCH.equals(intent.getAction())) if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
{
String query = intent.getStringExtra(SearchManager.QUERY); String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query); doSearch(query);
} else if(Intent.ACTION_VIEW.equals(intent.getAction())) { } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
} else { } else {
String intentMessage = intent.getStringExtra(EXTRA_MESSAGE); String intentMessage = intent.getStringExtra(EXTRA_MESSAGE);
if(intentMessage != null && intentMessage.contains(":")) { if (intentMessage != null && intentMessage.contains(":")) {
String[] position = intentMessage.split(":"); String[] position = intentMessage.split(":");
String latitude = position[0]; String latitude = position[0];
String longitude = position[1]; String longitude = position[1];
LatLng point = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude)); LatLng point = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL));
if(getIntent().hasExtra(AppConfig.EXTRA_MAP_TYPE)) mMarker = mMap.addMarker(new MarkerOptions().position(point)); if (getIntent().hasExtra(AppConfig.EXTRA_MAP_TYPE))
mMarker = mMap.addMarker(new MarkerOptions().position(point));
} else { } else {
LatLng myPosition = session.getLocation(); LatLng myPosition = session.getLocation();
if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) {
{
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myPosition.latitude, myPosition.longitude), DEFAULT_ZOOM_LEVEL)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myPosition.latitude, myPosition.longitude), DEFAULT_ZOOM_LEVEL));
}else{ } else {
getLocation(); getLocation();
} }
} }
@@ -698,7 +676,9 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
@Override @Override
public boolean onClusterClick(Cluster<IncidentReport> cluster) { return false; } public boolean onClusterClick(Cluster<IncidentReport> cluster) {
return false;
}
@Override @Override
public void onClusterItemInfoWindowClick(IncidentReport incidentReport) { public void onClusterItemInfoWindowClick(IncidentReport incidentReport) {
@@ -712,49 +692,50 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
handleIntent(intent); handleIntent(intent);
} }
private void doSearch(String query){ private void doSearch(String query) {
Bundle data = new Bundle(); Bundle data = new Bundle();
data.putString("query", query); data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this); getSupportLoaderManager().restartLoader(0, data, this);
} }
private void getPlace(String query){ private void getPlace(String query) {
Bundle data = new Bundle(); Bundle data = new Bundle();
data.putString("query", query); data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this); getSupportLoaderManager().restartLoader(1, data, this);
} }
private void showLocations(Cursor c){ private void showLocations(Cursor c) {
MarkerOptions markerOptions; MarkerOptions markerOptions;
LatLng position = null; LatLng position = null;
while(c.moveToNext()){ while (c.moveToNext()) {
markerOptions = new MarkerOptions(); markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2))); position = new LatLng(Double.parseDouble(c.getString(1)), Double.parseDouble(c.getString(2)));
markerOptions.position(position); markerOptions.position(position);
markerOptions.title(c.getString(0)); markerOptions.title(c.getString(0));
} }
if(position!=null){ if (position != null) {
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position); CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mMap.animateCamera(cameraPosition); mMap.animateCamera(cameraPosition);
} }
if (position != null) { if (position != null) {
myLocation = new LatLng(position.latitude,position.longitude); myLocation = new LatLng(position.latitude, position.longitude);
} }
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, DEFAULT_ZOOM_LEVEL)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, DEFAULT_ZOOM_LEVEL));
} }
@Override @Override
public void onLoaderReset(Loader<Cursor> arg0) {} public void onLoaderReset(Loader<Cursor> arg0) {
}
@Override @Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) { public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null; CursorLoader cLoader = null;
if(arg0==0) if (arg0 == 0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{query.getString("query") }, null); cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{query.getString("query")}, null);
else if(arg0==1) else if (arg0 == 1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null); cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{query.getString("query")}, null);
return cLoader; return cLoader;
} }
@@ -763,11 +744,11 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
@Override @Override
public void onLocationChanged(Location loc) { public void onLocationChanged(Location loc) {
if(loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) { if (loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) {
Log.d(TAG, "Save GPS as new location..."); Log.d(TAG, "Save GPS as new location...");
if(session.getLocation() == null || session.getLocation().latitude == 0.0 || session.getLocation().longitude == 0.0){ if (session.getLocation() == null || session.getLocation().latitude == 0.0 || session.getLocation().longitude == 0.0) {
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
}else{ } else {
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
} }
@@ -776,13 +757,16 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
@Override @Override
public void onProviderDisabled(String provider) {} public void onProviderDisabled(String provider) {
}
@Override @Override
public void onProviderEnabled(String provider) {} public void onProviderEnabled(String provider) {
}
@Override @Override
public void onStatusChanged(String provider, int status, Bundle extras) {} public void onStatusChanged(String provider, int status, Bundle extras) {
}
} }
private boolean isLocationEnabled() { private boolean isLocationEnabled() {
@@ -792,56 +776,50 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
public Location getLocation() { public Location getLocation() {
//check for permission //check for permission
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){ Log.d(TAG, "Permission for GPS not granted yet - ask for permission now");
Log.d(TAG,"Permission for GPS not granted yet - ask for permission now"); if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION); ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}else{ } else {
Log.d(TAG,"Permission for GPS granted - get position"); Log.d(TAG, "Permission for GPS granted - get position");
mMap.setMyLocationEnabled(true); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.frag_maps_map); locationListener = new MyLocationListener();
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
rlp.setMargins(0, 200, 30, 30);
try { try {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
if (!isLocationEnabled()) { if (!isLocationEnabled()) {
showMessage("Please activate GPS in your android settings."); showMessage("Please activate GPS in your android settings.");
Log.d(TAG,"Locationservice not enabled"); Log.d(TAG, "Locationservice not enabled");
} else { } else {
Log.d(TAG,"Locationservice enabled - check type"); Log.d(TAG, "Locationservice enabled - check type");
// if GPS Enabled get lat/long using GPS Services // if GPS Enabled get lat/long using GPS Services
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d(TAG,"Locationservice enabled - GPS Provider Found"); Log.d(TAG, "Locationservice enabled - GPS Provider Found");
if (location == null) { if (location == null) {
locationManager.requestLocationUpdates( locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS Enabled", "GPS Enabled"); Log.d(TAG, "GPS location from GPS Service activated");
if (locationManager != null) { if (locationManager != null) {
location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) { if (location != null) {
myLocation = new LatLng(location.getLatitude(),location.getLongitude()); myLocation = new LatLng(location.getLatitude(), location.getLongitude());
} }
} }
} }
}else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// get location from Network Provider // get location from Network Provider
Log.d(TAG,"Locationservice enabled - Network Provider Found"); Log.d(TAG, "Locationservice enabled - Network Provider Found");
locationManager.requestLocationUpdates( locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LocationManager.NETWORK_PROVIDER,
22, MIN_TIME_BW_UPDATES,
33, locationListener); MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("Network", "Network"); Log.d(TAG, "GPS location from Network Provider activated");
if (locationManager != null) { if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) { if (location != null) {
myLocation = new LatLng(location.getLatitude(),location.getLongitude()); myLocation = new LatLng(location.getLatitude(), location.getLongitude());
} }
} }
} }
@@ -858,6 +836,18 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
return location; return location;
} }
private void enableMyLocationButton() {
try{
mMap.setMyLocationEnabled(true);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.frag_maps_map);
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
rlp.setMargins(0, 250, 30, 30);
}catch(SecurityException se){
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
}
@Override @Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) { public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c); showLocations(c);
@@ -873,7 +863,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
SearchableInfo searchInfo = searchManager.getSearchableInfo(getComponentName()); SearchableInfo searchInfo = searchManager.getSearchableInfo(getComponentName());
searchView.setSearchableInfo(searchInfo); searchView.setSearchableInfo(searchInfo);
EditText txtSearch = ((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)); EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
txtSearch.setHint(getResources().getString(R.string.search_hint)); txtSearch.setHint(getResources().getString(R.string.search_hint));
txtSearch.setHintTextColor(Color.DKGRAY); txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(Color.BLACK); txtSearch.setTextColor(Color.BLACK);
@@ -882,9 +872,18 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
} }
@Override @Override
protected void onPause(){ protected void onPause() {
Log.d(TAG,"onPause executed: LM: "+(locationManager != null)+" LL: "+(locationListener!=null));
if(locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
locationListener = null;
locationManager = null;
}
super.onPause(); super.onPause();
if(showAdd) showAd();
if (showAdd) showAd();
} }
@Override @Override
@@ -897,21 +896,21 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
return getResources().getString(R.string.title_activity_maps); return getResources().getString(R.string.title_activity_maps);
} }
private void showProgress(){ private void showProgress() {
findViewById(R.id.pb_map_progress).setVisibility(View.VISIBLE); findViewById(R.id.pb_map_progress).setVisibility(View.VISIBLE);
pbCounter++; pbCounter++;
} }
@Override @Override
protected void onResume(){ protected void onResume() {
super.onResume(); super.onResume();
navDrawer.setSelection(mapAvtivityID, false); navDrawer.setSelection(mapAvtivityID, false);
showAdd = true; showAdd = true;
} }
private void hideProgress(){ private void hideProgress() {
pbCounter--; pbCounter--;
if(pbCounter == 0){ if (pbCounter == 0) {
findViewById(R.id.pb_map_progress).setVisibility(View.GONE); findViewById(R.id.pb_map_progress).setVisibility(View.GONE);
} }
} }

View File

@@ -459,7 +459,6 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen
private void finishReportAndGotoMap(IncidentReport incident) { private void finishReportAndGotoMap(IncidentReport incident) {
resetStateAndIncident(); resetStateAndIncident();
showAd();
gotoMapActivity(incident.getPosition().latitude + ":" + incident.getPosition().longitude); gotoMapActivity(incident.getPosition().latitude + ":" + incident.getPosition().longitude);
} }

View File

@@ -6,6 +6,9 @@ import android.support.v4.app.DialogFragment;
import android.app.TimePickerDialog; import android.app.TimePickerDialog;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@@ -46,19 +49,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
private Spinner timeCategory; private Spinner timeCategory;
private Spinner timeSubCategory; private Spinner timeSubCategory;
private EditText inputTimeFrom; private static EditText inputTimeFrom;
private EditText inputDateFrom; private static EditText inputDateFrom;
private EditText inputTimeTo; private static EditText inputTimeTo;
private EditText inputDateTo; private static EditText inputDateTo;
private EditText tmpInput; private static EditText tmpInput;
private IncidentReport incident; private IncidentReport incident;
private OnInputFinishedListener mCallback; private OnInputFinishedListener mCallback;
private boolean tmpIsToDate = false; public static boolean tmpIsToDate = false;
private boolean tmpIsToTime = false; public static boolean tmpIsToTime = false;
private DialogFragment timePickerFragment;
private DialogFragment datePickerFragment;
public interface OnInputFinishedListener { public interface OnInputFinishedListener {
void onInputFinished(boolean finished); void onInputFinished(boolean finished);
@@ -194,6 +200,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
tmpInput = inputDateFrom; tmpInput = inputDateFrom;
tmpInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
checkIfFinished();
}
});
showDatePickerDialog(); showDatePickerDialog();
} }
}); });
@@ -202,6 +224,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
tmpInput = inputTimeFrom; tmpInput = inputTimeFrom;
tmpInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
checkIfFinished();
}
});
showTimePickerDialog(); showTimePickerDialog();
} }
}); });
@@ -233,7 +271,7 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
}); });
} }
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@Override @Override
public Dialog onCreateDialog(Bundle savedInstanceState) { public Dialog onCreateDialog(Bundle savedInstanceState) {
@@ -247,17 +285,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) { public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
tmpInput.setText(String.format("%02d:%02d",hourOfDay,minute)); tmpInput.setText(String.format("%02d:%02d",hourOfDay,minute));
checkIfFinished(); //checkIfFinished();
} }
} }
public void showTimePickerDialog() { public void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment(); FragmentManager fm = getFragmentManager();
timePickerFragment = (TimePickerFragment) fm.findFragmentByTag("Pick Time");
newFragment.show(getActivity().getSupportFragmentManager(), "Pick Time"); if(timePickerFragment == null){
timePickerFragment = new TimePickerFragment();
}
timePickerFragment.show(fm, "Pick Time");
} }
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override @Override
public Dialog onCreateDialog(Bundle savedInstanceState) { public Dialog onCreateDialog(Bundle savedInstanceState) {
@@ -286,13 +329,20 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
public void onDateSet(DatePicker view, int year, int month, int day) { public void onDateSet(DatePicker view, int year, int month, int day) {
tmpInput.setText(String.format("%04d-%02d-%02d",year,month + 1,day)); tmpInput.setText(String.format("%04d-%02d-%02d",year,month + 1,day));
checkIfFinished(); //checkIfFinished();
} }
} }
public void showDatePickerDialog() { public void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "Pick Date"); FragmentManager fm = getFragmentManager();
datePickerFragment = (DatePickerFragment) fm.findFragmentByTag("Pick Date");
if(datePickerFragment == null){
datePickerFragment = new DatePickerFragment();
}
datePickerFragment.show(fm, "Pick Date");
} }
private void checkIfFinished(){ private void checkIfFinished(){
@@ -361,6 +411,25 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment {
checkIfFinished(); checkIfFinished();
} }
@Override
public void onStop() {
super.onStop();
//invalidate the DialogFragment to avoid stupid memory leak
if (timePickerFragment != null) {
if (timePickerFragment.isVisible()) {
timePickerFragment.dismiss();
}
timePickerFragment = null;
}
if (datePickerFragment != null) {
if (datePickerFragment.isVisible()) {
datePickerFragment.dismiss();
}
datePickerFragment = null;
}
}
@Override @Override
public void onPause() { public void onPause() {
super.onPause(); super.onPause();

View File

@@ -128,7 +128,9 @@ public class SettingsFragment extends PreferenceFragment {
prefLocation.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { prefLocation.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (session.getLocation().longitude != 0.0 && session.getLocation().latitude != 0.0) { if (session.getManualLocation().longitude != 0.0 && session.getManualLocation().latitude != 0.0) {
((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(Double.toString(session.getManualLocation().latitude) + " : " + Double.toString(session.getManualLocation().longitude));
} else if(session.getLocation().longitude != 0.0 && session.getLocation().latitude != 0.0){
((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(Double.toString(session.getLocation().latitude) + " : " + Double.toString(session.getLocation().longitude)); ((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(Double.toString(session.getLocation().latitude) + " : " + Double.toString(session.getLocation().longitude));
} else { } else {
((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(); ((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity();
@@ -218,7 +220,7 @@ public class SettingsFragment extends PreferenceFragment {
prefRadius.setValue(Integer.toString(session.getNotificationRadius())); prefRadius.setValue(Integer.toString(session.getNotificationRadius()));
prefRadius.setSummary(prefRadius.getEntry()); prefRadius.setSummary(prefRadius.getEntry());
prefGPSENabled.setChecked(session.isGPSForNotificationsEnabled()); prefGPSENabled.setChecked(session.isGPSForNotificationsEnabled());
prefLocation.setSummary(getResources().getString(R.string.txt_settings_gps_loca_sum)+":\n"+Double.toString(session.getLocation().latitude)+" : "+Double.toString(session.getLocation().longitude)); prefLocation.setSummary(getResources().getString(R.string.txt_settings_gps_loca_sum)+":\n"+Double.toString(session.getManualLocation().latitude)+" : "+Double.toString(session.getManualLocation().longitude));
if(session.getSubsPremium()){ if(session.getSubsPremium()){
if(session.isGPSForNotificationsEnabled()){ if(session.isGPSForNotificationsEnabled()){

View File

@@ -71,11 +71,9 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
*
* (C) Copyright 2016 RiskAhead (http://www.riskahead.net) * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
* Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
* Date of Release: 10.02.2016 * Date of Release: 10.02.2016
*
*/ */
public abstract class BaseActivity extends AppCompatActivity { public abstract class BaseActivity extends AppCompatActivity {
@@ -106,14 +104,14 @@ public abstract class BaseActivity extends AppCompatActivity {
int onStartCount = 0; int onStartCount = 0;
public void userHasToBeLoggedIn(){ public void userHasToBeLoggedIn() {
if (!session.isLoggedIn()) { if (!session.isLoggedIn()) {
logout(); logout();
} }
isNetworkAvailable(); isNetworkAvailable();
} }
public HashMap<String, String> getUser(){ public HashMap<String, String> getUser() {
user = session.getUserDetails(); user = session.getUserDetails();
return user; return user;
} }
@@ -137,14 +135,11 @@ public abstract class BaseActivity extends AppCompatActivity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
onStartCount = 1; onStartCount = 1;
if (savedInstanceState == null) if (savedInstanceState == null) {
{
this.overridePendingTransition(R.anim.slide_in_left, this.overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_left); R.anim.slide_out_left);
} else } else {
{
onStartCount = 2; onStartCount = 2;
} }
@@ -156,22 +151,15 @@ public abstract class BaseActivity extends AppCompatActivity {
session = new SessionManager(getApplicationContext()); session = new SessionManager(getApplicationContext());
user = session.getUserDetails(); user = session.getUserDetails();
Log.d(TAG,user.get(SessionManager.KEY_UID)); Log.d(TAG, user.get(SessionManager.KEY_UID));
mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar); setSupportActionBar(mToolbar);
initNavigationDrawer(savedInstanceState); initNavigationDrawer(savedInstanceState);
if (!isMyNotificationServiceRunning()) {
if(!isMyNotificationServiceRunning() && session.getNotificationEnabled()){ Log.d(TAG, "onCreate: NotificationService not running. Starting service...");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1);
return;
}
Log.d(TAG,"onCreate: NotificationService not running. Starting service...");
Intent wtdSServiceIntent = new Intent(this, NotificationService.class); Intent wtdSServiceIntent = new Intent(this, NotificationService.class);
PendingIntent wtdSServicePendingIntent = PendingIntent.getService(this, 0, wtdSServiceIntent, 0); PendingIntent wtdSServicePendingIntent = PendingIntent.getService(this, 0, wtdSServiceIntent, 0);
@@ -182,13 +170,12 @@ public abstract class BaseActivity extends AppCompatActivity {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC, firstStart, interval, am.setInexactRepeating(AlarmManager.RTC, firstStart, interval,
wtdSServicePendingIntent); wtdSServicePendingIntent);
Log.d(TAG, "AlarmManager set");
startService(new Intent(this, NotificationService.class)); startService(new Intent(this, NotificationService.class));
}else{ } else {
Log.d(TAG,"onCreate: NotificationService already running. Not starting more services."); Log.d(TAG, "onCreate: NotificationService already running. Not starting more services.");
} }
AppRater.app_launched(BaseActivity.this); AppRater.app_launched(BaseActivity.this);
@@ -203,30 +190,29 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
@Override @Override
protected void onDestroy(){ protected void onDestroy() {
super.onDestroy(); super.onDestroy();
unregisterBroadcastReceiver(); unregisterBroadcastReceiver();
} }
@Override @Override
protected void onResume(){ protected void onResume() {
super.onResume(); super.onResume();
registerBroadcastReceiver(); registerBroadcastReceiver();
} }
public void registerBroadcastReceiver(){ public void registerBroadcastReceiver() {
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AppConfig.INTENT_LOGOUT); intentFilter.addAction(AppConfig.INTENT_LOGOUT);
myReceiver = new LogoutReceiver(); myReceiver = new LogoutReceiver();
registerReceiver(myReceiver, intentFilter); registerReceiver(myReceiver, intentFilter);
} }
public void unregisterBroadcastReceiver(){ public void unregisterBroadcastReceiver() {
try{ try {
unregisterReceiver(myReceiver); unregisterReceiver(myReceiver);
}catch(final Exception e){ } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -305,7 +291,7 @@ public abstract class BaseActivity extends AppCompatActivity {
@Override @Override
public void onDrawerClosed(View drawerView) { public void onDrawerClosed(View drawerView) {
android.support.v7.app.ActionBar actionBar = getSupportActionBar(); android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar != null) actionBar.setTitle(getActivityName()); if (actionBar != null) actionBar.setTitle(getActivityName());
} }
@Override @Override
@@ -324,38 +310,37 @@ public abstract class BaseActivity extends AppCompatActivity {
new DividerDrawerItem(), new DividerDrawerItem(),
item6, item6,
item7).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { item7).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override @Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch ((int)drawerItem.getIdentifier()) { switch ((int) drawerItem.getIdentifier()) {
case 2: case 2:
gotoReportActivity(); gotoReportActivity();
return false; return false;
case 3: case 3:
gotoMapActivity(); gotoMapActivity();
return false; return false;
case 4: case 4:
gotoProfileActivity(); gotoProfileActivity();
return false; return false;
case 5: case 5:
gotoSettingsActivity(); gotoSettingsActivity();
return false; return false;
case 6: case 6:
gotoSubscriptionsActivity(); gotoSubscriptionsActivity();
return false; return false;
case 7: case 7:
logoutUser(); logoutUser();
break; break;
default: default:
Log.d("Unknown switch page: ", Integer.toString(position)); Log.d("Unknown switch page: ", Integer.toString(position));
break; break;
} }
return false;
}
}).build();
return false;
}
}).build();
} }
@@ -366,25 +351,23 @@ public abstract class BaseActivity extends AppCompatActivity {
mInterstitialAd.loadAd(adRequest); mInterstitialAd.loadAd(adRequest);
} }
public void showAd(){ public void showAd() {
if(System.currentTimeMillis() == 0) session.setLastAddShown(System.currentTimeMillis()); if (session.getLastAddShown() == 0) session.setLastAddShown(System.currentTimeMillis());
if(System.currentTimeMillis() > session.getLastAddShown()+120000){ if (System.currentTimeMillis() > (session.getLastAddShown() + 120000)) {
Log.d(TAG, "SHOW ADD!"); Log.d(TAG, "SHOW ADD!");
if (mInterstitialAd.isLoaded()) { if (mInterstitialAd.isLoaded()) {
Log.d(TAG, "Loading Add..."); Log.d(TAG, "Loading Add...");
if(!(session.getSubsNoAds() || session.getSubsPremium())){ if (!(session.getSubsNoAds() || session.getSubsPremium())) {
mInterstitialAd.show(); mInterstitialAd.show();
session.setLastAddShown(System.currentTimeMillis()); session.setLastAddShown(System.currentTimeMillis());
} else {
}else{ Log.d(TAG, "Add not shown because user has status.");
Log.d(TAG,"Add not shown because user has status."); }
} }
} } else {
}else{
Log.d(TAG, "SHOW NO ADD ( TIME NOT OUT ) !"); Log.d(TAG, "SHOW NO ADD ( TIME NOT OUT ) !");
} }
} }
@@ -393,7 +376,7 @@ public abstract class BaseActivity extends AppCompatActivity {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo == null){ if (activeNetworkInfo == null) {
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
.setTitle(getString(R.string.alert_internetconnection_title)) .setTitle(getString(R.string.alert_internetconnection_title))
.setMessage(getString(R.string.alert_internetconnection_text)) .setMessage(getString(R.string.alert_internetconnection_text))
@@ -441,13 +424,13 @@ public abstract class BaseActivity extends AppCompatActivity {
return true; return true;
} }
public void gotoReportActivity(){ public void gotoReportActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), ReportWFActivity.class); intent = new Intent(getApplicationContext(), ReportWFActivity.class);
startActivity(intent); startActivity(intent);
} }
public void gotoReportActivity(String position){ public void gotoReportActivity(String position) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), ReportWFActivity.class); intent = new Intent(getApplicationContext(), ReportWFActivity.class);
intent.putExtra(EXTRA_MESSAGE, position); intent.putExtra(EXTRA_MESSAGE, position);
@@ -455,34 +438,34 @@ public abstract class BaseActivity extends AppCompatActivity {
finish(); finish();
} }
public void gotoMapActivity(){ public void gotoMapActivity() {
Intent intent; Intent intent;
intent = new Intent(BaseActivity.this, MapsActivity.class); intent = new Intent(BaseActivity.this, MapsActivity.class);
BaseActivity.this.startActivity(intent); BaseActivity.this.startActivity(intent);
} }
public void gotoMapActivity(String position){ public void gotoMapActivity(String position) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), MapsActivity.class); intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra(EXTRA_MESSAGE, position); intent.putExtra(EXTRA_MESSAGE, position);
startActivity(intent); startActivity(intent);
} }
public void getNotifyLocationFromMapActivity(){ public void getNotifyLocationFromMapActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), MapsActivity.class); intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETNOTIFY); intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETNOTIFY);
startActivity(intent); startActivity(intent);
} }
public void getIncidentLocationFromMapActivity(){ public void getIncidentLocationFromMapActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), MapsActivity.class); intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETINCLOC); intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETINCLOC);
startActivity(intent); startActivity(intent);
} }
public void getNotifyLocationFromMapActivity(String position){ public void getNotifyLocationFromMapActivity(String position) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), MapsActivity.class); intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra(EXTRA_MESSAGE, position); intent.putExtra(EXTRA_MESSAGE, position);
@@ -490,7 +473,7 @@ public abstract class BaseActivity extends AppCompatActivity {
startActivity(intent); startActivity(intent);
} }
public void getIncidentLocationFromMapActivity(String position){ public void getIncidentLocationFromMapActivity(String position) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), MapsActivity.class); intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra(EXTRA_MESSAGE, position); intent.putExtra(EXTRA_MESSAGE, position);
@@ -498,32 +481,32 @@ public abstract class BaseActivity extends AppCompatActivity {
startActivity(intent); startActivity(intent);
} }
public void gotoProfileActivity(){ public void gotoProfileActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), ProfileActivity.class); intent = new Intent(getApplicationContext(), ProfileActivity.class);
startActivity(intent); startActivity(intent);
} }
public void gotoProfileActivity(String uid){ public void gotoProfileActivity(String uid) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), ProfileActivity.class); intent = new Intent(getApplicationContext(), ProfileActivity.class);
intent.putExtra(EXTRA_MESSAGE, uid); intent.putExtra(EXTRA_MESSAGE, uid);
startActivity(intent); startActivity(intent);
} }
public void gotoSettingsActivity(){ public void gotoSettingsActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), SettingsActivity.class); intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent); startActivity(intent);
} }
public void gotoSubscriptionsActivity(){ public void gotoSubscriptionsActivity() {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), SubscriptionsActivity.class); intent = new Intent(getApplicationContext(), SubscriptionsActivity.class);
startActivity(intent); startActivity(intent);
} }
public void gotoViewReportActivity(Integer uid){ public void gotoViewReportActivity(Integer uid) {
Intent intent; Intent intent;
intent = new Intent(getApplicationContext(), ViewReportActivity.class); intent = new Intent(getApplicationContext(), ViewReportActivity.class);
intent.putExtra(EXTRA_MESSAGE, uid); intent.putExtra(EXTRA_MESSAGE, uid);
@@ -534,36 +517,36 @@ public abstract class BaseActivity extends AppCompatActivity {
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if((id == R.id.menu_action_exit)){ if ((id == R.id.menu_action_exit)) {
Intent intent = new Intent(Intent.ACTION_MAIN); Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME); intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); startActivity(intent);
}else if((id == R.id.menu_action_about)){ } else if ((id == R.id.menu_action_about)) {
showAboutInfoDialog(); showAboutInfoDialog();
}else if((id == R.id.menu_action_language)){ } else if ((id == R.id.menu_action_language)) {
showLanguageDialog(); showLanguageDialog();
}else if((id == R.id.menu_action_help)){ } else if ((id == R.id.menu_action_help)) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.riskahead.net/contact/")); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.riskahead.net/contact/"));
startActivity(browserIntent); startActivity(browserIntent);
}else if((id == R.id.menu_action_feedback)){ } else if ((id == R.id.menu_action_feedback)) {
showFeedbackDialog(); showFeedbackDialog();
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
private void showLanguageDialog(){ private void showLanguageDialog() {
AlertDialog.Builder b = new AlertDialog.Builder(this); AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(R.string.txt_language_title); b.setTitle(R.string.txt_language_title);
String[] types = {"ar - العربية", "de - Deutsch", "en - English", "es - Español", "et - Eesti keel", "fi - Suomi", "fr - Français", "lv - Latviešu valoda", "mn - Монгол хэл", "nl - Nederlands", "pl - Polszczyzna", "pt - Português do Brasil", "ru - Pусский", "tr - Türkçe"}; String[] types = {"ar - العربية", "de - Deutsch", "en - English", "es - Español", "et - Eesti keel", "fi - Suomi", "fr - Français", "lv - Latviešu valoda", "mn - Монгол хэл", "nl - Nederlands", "pl - Polszczyzna", "pt - Português do Brasil", "ru - Pусский", "tr - Türkçe"};
b.setItems(types, new DialogInterface.OnClickListener() { b.setItems(types, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); dialog.dismiss();
switch(which){ switch (which) {
case 0: case 0:
setLocale("ar"); setLocale("ar");
break; break;
@@ -635,12 +618,12 @@ public abstract class BaseActivity extends AppCompatActivity {
((TextView) dialoglayout.findViewById(R.id.txt_about_terms)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) dialoglayout.findViewById(R.id.txt_about_terms)).setMovementMethod(LinkMovementMethod.getInstance());
try { try {
((TextView) dialoglayout.findViewById(R.id.lbl_about_version)).setText(String.format("Version: %s",getPackageManager().getPackageInfo(getPackageName(), 0).versionName)); ((TextView) dialoglayout.findViewById(R.id.lbl_about_version)).setText(String.format("Version: %s", getPackageManager().getPackageInfo(getPackageName(), 0).versionName));
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this) AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
//do nothing //do nothing
@@ -652,7 +635,7 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
private void showFeedbackDialog() { private void showFeedbackDialog() {
AlertDialog.Builder alert=new AlertDialog.Builder(this); AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.menu_action_feedback); alert.setTitle(R.string.menu_action_feedback);
alert.setMessage(R.string.txt_feedback_message); alert.setMessage(R.string.txt_feedback_message);
@@ -664,7 +647,7 @@ public abstract class BaseActivity extends AppCompatActivity {
input.setLayoutParams(lp); input.setLayoutParams(lp);
input.setLines(4); input.setLines(4);
input.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),R.color.bootstrap_gray_lightest)); input.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.bootstrap_gray_lightest));
input.setGravity(Gravity.TOP); input.setGravity(Gravity.TOP);
input.setHint(R.string.txt_feedback_hint); input.setHint(R.string.txt_feedback_hint);
@@ -686,7 +669,7 @@ public abstract class BaseActivity extends AppCompatActivity {
}); });
AlertDialog ad = alert.create(); AlertDialog ad = alert.create();
ad.setView(input,0,50,0,20); ad.setView(input, 0, 50, 0, 20);
ad.show(); ad.show();
} }
@@ -697,11 +680,11 @@ public abstract class BaseActivity extends AppCompatActivity {
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
String k = (String) e.nextElement(); String k = (String) e.nextElement();
String v = props.getProperty(k); String v = props.getProperty(k);
sysprop += k+": "+v+"\n"; sysprop += k + ": " + v + "\n";
} }
StringRequest strReq = getStringRequestSendFeedback(feedback,sysprop); StringRequest strReq = getStringRequestSendFeedback(feedback, sysprop);
String tag_string_req = "reqsendfeedback"; String tag_string_req = "reqsendfeedback";
AppController.getInstance().addToRequestQueue(strReq, tag_string_req); AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
} }
@@ -748,7 +731,7 @@ public abstract class BaseActivity extends AppCompatActivity {
}; };
} }
public void showMessage(String statusText){ public void showMessage(String statusText) {
Toast.makeText(this, statusText, Toast.LENGTH_LONG).show(); Toast.makeText(this, statusText, Toast.LENGTH_LONG).show();
} }
@@ -795,5 +778,4 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
} }

View File

@@ -51,11 +51,16 @@ public class NotificationService extends Service {
private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
private static int gpscounter = 0;
public SessionManager session; public SessionManager session;
public HashMap<String, String> user; public HashMap<String, String> user;
public LocationManager locationManager; private LocationManager locationManager;
private LocationListener locationListener;
private LatLng myPosition;
public NotificationService() { public NotificationService() {
super(); super();
@@ -63,75 +68,87 @@ public class NotificationService extends Service {
@Override @Override
public void onCreate() { public void onCreate() {
Log.d(TAG, "onCreate NotificationService");
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
session = new SessionManager(getApplicationContext()); session = new SessionManager(getApplicationContext());
user = session.getUserDetails(); user = session.getUserDetails();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Log.d(TAG, "NotificationService created. Starting notification task...");
LocationListener locationListener = new MyLocationListener(); mNotifyTask.run();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { private void initAndGetPosition() {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d(TAG,"Trying to get a position. GPS enabled: "+session.isGPSForNotificationsEnabled());
Log.d(TAG,"Locationservice enabled - GPS Provider Found"); if(session.isGPSForNotificationsEnabled()) {
locationManager.requestLocationUpdates( if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationManager.GPS_PROVIDER, locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MIN_TIME_BW_UPDATES, locationListener = new MyLocationListener();
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.d(TAG, "Locationservice enabled - GPS Provider Found");
if (tmpLocation != null) {
session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()),Double.doubleToRawLongBits(tmpLocation.getLongitude())); locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d(TAG, "GPS Provider enabled");
if (locationManager != null) {
Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (tmpLocation != null) {
Log.d(TAG,"Last known position found from GPS Provider");
removeLocationListener();
session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()), Double.doubleToRawLongBits(tmpLocation.getLongitude()));
myPosition = session.getLocation();
session.setNotificationServiceReady(true);
}
} }
} } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
}else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { // get location from Network Provider
// get location from Network Provider Log.d(TAG, "Locationservice enabled - Network Provider Found");
Log.d(TAG,"Locationservice enabled - Network Provider Found"); locationManager.requestLocationUpdates(
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
22, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
33, locationListener); Log.d(TAG, "Network Provider enabled");
Log.d("Network", "Network"); if (locationManager != null) {
if (locationManager != null) { Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (tmpLocation != null) {
if (tmpLocation != null) { Log.d(TAG,"Last known position found from Network Provider");
session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()),Double.doubleToRawLongBits(tmpLocation.getLongitude())); removeLocationListener();
session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()), Double.doubleToRawLongBits(tmpLocation.getLongitude()));
myPosition = session.getLocation();
session.setNotificationServiceReady(true);
}
} }
} }
} }
}else{
myPosition = session.getManualLocation();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, locationListener);
} }
}
Log.d(TAG, "Service Created. Starting notification task..."); private void removeLocationListener() {
mNotifyTask.run(); if(locationManager != null && locationListener != null){
locationManager.removeUpdates(locationListener);
locationListener = null;
locationManager = null;
}
} }
private class MyLocationListener implements LocationListener { private class MyLocationListener implements LocationListener {
@Override @Override
public void onLocationChanged(Location loc) { public void onLocationChanged(Location loc) {
if(session.isGPSForNotificationsEnabled() && loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) { Log.d(TAG,"onLocationChanged: "+gpscounter);
Log.d(TAG, "Save GPS as new location..."); session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
if(session.getLocation() == null || session.getLocation().latitude == 0.0 || session.getLocation().longitude == 0.0){ session.setNotificationServiceReady(true);
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
mNotifyHandler.removeCallbacksAndMessages(null);
mNotifyTask.run();
}else{
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
}
session.setNotificationServiceReady(true); if(gpscounter > 3){
removeLocationListener();
}else{
Log.d(TAG,"Don't Save GPS as new location because GPS for notifications is disabled...: "+session.isGPSForNotificationsEnabled());
} }
gpscounter++;
} }
@Override @Override
@@ -154,14 +171,15 @@ public class NotificationService extends Service {
public void run() { public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
LatLng myPosition = session.getLocation(); boolean notifyEnabled = session.getNotificationEnabled();
int radius = session.getNotificationRadius(); int radius = session.getNotificationRadius();
int pollFrequency = session.getNotificationPollFreq() * 1000 * 60; int pollFrequency = session.getNotificationPollFreq() * 1000 * 60;
boolean notifyEnabled = session.getNotificationEnabled();
Log.d(this.toString(), "Run Notification Task. Notifications enabled = " + notifyEnabled); Log.d(this.toString(), "Run Notification Task. Notifications enabled = " + notifyEnabled);
if(notifyEnabled && session.isLoggedIn()){ if(notifyEnabled && session.isLoggedIn()){
initAndGetPosition();
if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) { if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) {
session.setNotificationServiceReady(true); session.setNotificationServiceReady(true);
String lastNotificationTime; String lastNotificationTime;
@@ -172,7 +190,7 @@ public class NotificationService extends Service {
lastNotificationTime = session.getLastNotification(); lastNotificationTime = session.getLastNotification();
} }
Log.d(this.toString(), "Lookup location with position: " + myPosition + " Radius: "+ radius +" PollFrequency: "+ pollFrequency +" lastNotifyTime: " + lastNotificationTime); Log.d(this.toString(), "Lookup location with position: " + myPosition + " Radius: "+ radius +" PollFrequency: "+ pollFrequency +" lastNotifyTime: " + lastNotificationTime + " GPSActivated: "+session.isGPSForNotificationsEnabled());
StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, radius, lastNotificationTime); StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, radius, lastNotificationTime);
String tag_string_req = "req_incidents"; String tag_string_req = "req_incidents";
@@ -272,18 +290,16 @@ public class NotificationService extends Service {
); );
mBuilder.setContentIntent(resultPendingIntent); mBuilder.setContentIntent(resultPendingIntent);
int mId = 1; mNotificationManager.notify(1, mBuilder.build());
mNotificationManager.notify(mId, mBuilder.build());
session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())); session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
} }
@Override @Override
public void onDestroy(){ public void onDestroy(){
if(locationManager != null && locationListener != null) locationManager.removeUpdates(locationListener);
super.onDestroy(); super.onDestroy();
Log.d(TAG, "Destroy NotificationService"); Log.d(TAG, "Destroy NotificationService");
} }
} }

View File

@@ -49,6 +49,9 @@ public class SessionManager {
public static final String KEY_LOCATION_LAT = "location_latitude"; public static final String KEY_LOCATION_LAT = "location_latitude";
public static final String KEY_LOCATION_LNG = "location_longitude"; public static final String KEY_LOCATION_LNG = "location_longitude";
public static final String KEY_MAN_LOCATION_LAT = "man_location_latitude";
public static final String KEY_MAN_LOCATION_LNG = "man_location_longitude";
public static final String KEY_LAST_NOTIFICATION = "lastNotificationTime"; public static final String KEY_LAST_NOTIFICATION = "lastNotificationTime";
public static final String KEY_NOTIFY_ENABLED = "notifyEnabled" ; public static final String KEY_NOTIFY_ENABLED = "notifyEnabled" ;
public static final String KEY_NOTIFY_RADIUS = "notifyRadius"; public static final String KEY_NOTIFY_RADIUS = "notifyRadius";
@@ -88,6 +91,16 @@ public class SessionManager {
return new LatLng(Double.longBitsToDouble(status.getLong(KEY_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_LOCATION_LNG, 0))); return new LatLng(Double.longBitsToDouble(status.getLong(KEY_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_LOCATION_LNG, 0)));
} }
public void setManualLocation(Long latitude, Long longitude){
statusEditor.putLong(KEY_MAN_LOCATION_LAT, latitude);
statusEditor.putLong(KEY_MAN_LOCATION_LNG, longitude);
statusEditor.apply();
}
public LatLng getManualLocation(){
return new LatLng(Double.longBitsToDouble(status.getLong(KEY_MAN_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_MAN_LOCATION_LNG, 0)));
}
public void setGPSForNotificationsEnabled(boolean isEnabled){ public void setGPSForNotificationsEnabled(boolean isEnabled){
statusEditor.putBoolean(KEY_NOTIFY_GPS, isEnabled); statusEditor.putBoolean(KEY_NOTIFY_GPS, isEnabled);
statusEditor.apply(); statusEditor.apply();

View File

@@ -248,43 +248,43 @@
</string-array> </string-array>
<string-array name="cat_situation_sub_threat"> <string-array name="cat_situation_sub_threat">
<item>Robbery</item> <item>Überfall</item>
<item>Drug related</item> <item>Drogenkriminalität</item>
<item>Strike/Riot</item> <item>Streik/Aufstand</item>
<item>Checkpoint/Blockade</item> <item>Checkpoint/Blockade</item>
<item>Corruption/Extorsion</item> <item>Korruption/Missbrauch</item>
</string-array> </string-array>
<string-array name="cat_situation_sub_physical"> <string-array name="cat_situation_sub_physical">
<item>Mugging</item> <item>Raubüberfall</item>
<item>Sexual Assault</item> <item>Sexuelle Belästigung</item>
<item>Physical Attack</item> <item>Physischer Angriff</item>
<item>Fight</item> <item>Kampf</item>
<item>Arrest/Capture</item> <item>Arrest/Übernahme</item>
<item>Forced Labour</item> <item>Zwangsarbeit</item>
</string-array> </string-array>
<string-array name="cat_situation_sub_lifethreat"> <string-array name="cat_situation_sub_lifethreat">
<item>Rape</item> <item>Vergewaltigung</item>
<item>Kidnapping/Hostage</item> <item>Geiselnahme</item>
<item>Shooting</item> <item>Schießerei</item>
<item>Bombing</item> <item>Bombenangriff</item>
<item>Murder</item> <item>Mord</item>
<item>Dead body</item> <item>Leiche</item>
</string-array> </string-array>
<string-array name="cat_situation_sub_disaster"> <string-array name="cat_situation_sub_disaster">
<item>Heat Wave</item> <item>Hitzewelle</item>
<item>Cyclone/Tornado</item> <item>Tornado</item>
<item>Flood</item> <item>Flut</item>
<item>Earthquake</item> <item>Erdbeben</item>
<item>Wild Fire</item> <item>Wildfeuer</item>
<item>Volcano</item> <item>Vulkanausbruch</item>
<item>Tsunami</item> <item>Tsunami</item>
<item>Fire</item> <item>Feuer</item>
<item>Chemical/Oil Spill</item> <item>Chemie-/Ölunfall</item>
<item>Epidemic</item> <item>Epidemie</item>
<item>Chaos/Anarchy</item> <item>Chaos/Anarchie</item>
</string-array> </string-array>
<string-array name="cat_time_main"> <string-array name="cat_time_main">

View File

@@ -6,7 +6,7 @@ buildscript {
maven { url 'https://maven.fabric.io/public' } maven { url 'https://maven.fabric.io/public' }
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:2.3.0' classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.google.gms:google-services:1.3.0-beta3' classpath 'com.google.gms:google-services:1.3.0-beta3'
classpath 'io.fabric.tools:gradle:1.+' classpath 'io.fabric.tools:gradle:1.+'
} }