From 136806adfda29bad3c885cce40d1d1209f39a514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mieszko=20Wrzeszczy=C5=84ski?= Date: Sun, 30 Sep 2018 22:56:53 +0200 Subject: [PATCH 1/2] Send real data from service && a little refactor --- app/src/main/AndroidManifest.xml | 2 +- .../findmytutor/activity/LoginActivity.java | 4 +- .../findmytutor/activity/MainActivity.java | 45 +---- .../uam/wmi/findmytutor/model/Coordinate.java | 1 - ...ava => BackgroundLocalizationService.java} | 13 +- .../service/CoordinateService.java | 31 +--- .../service/LocationRequestHelper.java | 39 ---- .../service/LocationResultHelper.java | 158 ---------------- .../findmytutor/service/LocationService.java | 173 ------------------ .../utils/BroadcastLocalizationHandler.java | 22 +-- .../utils/MyDividerItemDecoration.java | 98 ---------- .../utils/RecyclerTouchListener.java | 54 ------ 12 files changed, 29 insertions(+), 611 deletions(-) rename app/src/main/java/com/uam/wmi/findmytutor/service/{GoogleService.java => BackgroundLocalizationService.java} (94%) delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/service/LocationRequestHelper.java delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/service/LocationResultHelper.java delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/service/LocationService.java delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/utils/MyDividerItemDecoration.java delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/utils/RecyclerTouchListener.java diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c687fb4..832b185 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -54,7 +54,7 @@ + android:name=".service.BackgroundLocalizationService"/> diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java index f4c1356..0c2dbc5 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java @@ -211,7 +211,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); - mAuthTask = new UserLoginTask(email, password,loginOption); + mAuthTask = new UserLoginTask(email, password, loginOption); mAuthTask.execute((Void) null); } } @@ -354,10 +354,10 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< @Override public void onSuccess(JwtToken jwtToken) { String token = jwtToken.getToken(); + JWT jwt = new JWT(token); Claim role = jwt.getClaim("nameid"); - Log.e("user",role.asString()); PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeUserId(getApplicationContext(), role.asString()); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java index 3192f19..c69849b 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java @@ -6,24 +6,17 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; -import android.location.Address; -import android.location.Geocoder; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; -import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; -import com.uam.wmi.findmytutor.model.Coordinate; -import com.uam.wmi.findmytutor.model.LdapUser; -import com.uam.wmi.findmytutor.network.ApiClient; -import com.uam.wmi.findmytutor.service.CoordinateService; -import com.uam.wmi.findmytutor.service.GoogleService; +import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; import android.support.design.widget.FloatingActionButton; import android.app.Fragment; @@ -35,24 +28,9 @@ import android.view.MenuItem; import com.mapbox.mapboxsdk.Mapbox; import com.uam.wmi.findmytutor.R; -import com.uam.wmi.findmytutor.service.LdapService; -import com.uam.wmi.findmytutor.service.LocationService; import com.uam.wmi.findmytutor.utils.BroadcastLocalizationHandler; import com.uam.wmi.findmytutor.utils.PrefUtils; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; - -import java.io.IOException; -import java.util.List; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.observers.DisposableSingleObserver; -import io.reactivex.schedulers.Schedulers; -import timber.log.Timber; - public class MainActivity extends AppCompatActivity { private BottomNavigationView mMainNav; @@ -63,18 +41,11 @@ public class MainActivity extends AppCompatActivity { private ProfileFragment profileFragment; public static Intent backgroundLocalizationService = null; - ; private BroadcastReceiver broadcastReceiver = null; private static final int REQUEST_PERMISSIONS = 100; private boolean boolean_permission = false; - Double latitude, longitude; - - /* CompositeDisposable disposable = new CompositeDisposable(); - CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) - .create(CoordinateService.class);*/ - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -140,12 +111,7 @@ public class MainActivity extends AppCompatActivity { fn_permission(); - - - this.broadcastReceiver = new BroadcastLocalizationHandler(); - - } private void setFragment(Fragment fragment) { @@ -159,19 +125,17 @@ public class MainActivity extends AppCompatActivity { if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) { - } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_PERMISSIONS); - } } else { boolean_permission = true; if (boolean_permission) { if (!PrefUtils.getIsServiceRunning(getApplicationContext())) { - Intent intent = new Intent(getApplicationContext(), GoogleService.class); + Intent intent = new Intent(getApplicationContext(), BackgroundLocalizationService.class); startService(intent); } else { Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show(); @@ -181,9 +145,6 @@ public class MainActivity extends AppCompatActivity { } } - - - } @Override @@ -205,7 +166,7 @@ public class MainActivity extends AppCompatActivity { @Override protected void onResume() { super.onResume(); - registerReceiver(this.broadcastReceiver, new IntentFilter(GoogleService.str_receiver)); + registerReceiver(this.broadcastReceiver, new IntentFilter(BackgroundLocalizationService.str_receiver)); } @Override diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java index cc98df8..5624324 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java @@ -44,7 +44,6 @@ public class Coordinate extends BaseResponse { this.longitude = longitude; this.userId = userId; this.label = label; - } public Coordinate (Double latitude) { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/GoogleService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java similarity index 94% rename from app/src/main/java/com/uam/wmi/findmytutor/service/GoogleService.java rename to app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java index 0d0398d..74e338e 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/GoogleService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java @@ -2,7 +2,6 @@ package com.uam.wmi.findmytutor.service; import android.Manifest; import android.app.Service; -import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; @@ -13,12 +12,8 @@ import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; -import android.support.v4.content.LocalBroadcastManager; -import android.util.Log; -import com.uam.wmi.findmytutor.utils.PrefUtils; - import java.util.Timer; import java.util.TimerTask; @@ -26,7 +21,7 @@ import java.util.TimerTask; * Created by deepshikha on 24/11/16. */ -public class GoogleService extends Service implements LocationListener{ +public class BackgroundLocalizationService extends Service implements LocationListener{ boolean isGPSEnable = false; @@ -41,7 +36,7 @@ public class GoogleService extends Service implements LocationListener{ Intent intent; - public GoogleService() {} + public BackgroundLocalizationService() {} @Nullable @Override @@ -60,7 +55,7 @@ public class GoogleService extends Service implements LocationListener{ @Override public void onLocationChanged(Location location) { - + fn_getlocation(); } @Override @@ -142,7 +137,7 @@ public class GoogleService extends Service implements LocationListener{ private class TimerTaskToGetLocation extends TimerTask{ @Override public void run() { - mHandler.post(GoogleService.this::fn_getlocation); + mHandler.post(BackgroundLocalizationService.this::fn_getlocation); } } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java index ea0b31b..987e666 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java @@ -23,47 +23,32 @@ import retrofit2.http.Path; public interface CoordinateService { @GET("api/coordinates") - Call> getAllCoordinates(); + Single> getAllCoordinates(); @GET("api/coordinates/{id}") - Call getCoordinatesById(@Path("id") String id); + Single getCoordinatesById(@Path("id") String id); @GET("api/coordinates/user/{userId}") - Call> getCoordinatesByUserId(@Path("userId") String userId); + Single> getCoordinatesByUserId(@Path("userId") String userId); @GET("api/coordinates/userTop/{userId}") - Call> getTopCoordinatesByUserId(@Path("userId") String userId); + Single> getTopCoordinatesByUserId(@Path("userId") String userId); @GET("api/coordinates/top") - Call> getTopCoordinates(); + Single> getTopCoordinates(); @GET("api/coordinates/top/online") - Call> getOnlineCoordinates(); - -/* - - //works - @POST("api/coordinates") - Call postCoordinate(@Body RequestBody Coordinate); -*/ - + Single> getOnlineCoordinates(); //works @POST("api/coordinates") Single postCoordinate(@Body Coordinate coordinate); - - /* - // Create note - @FormUrlEncoded - @POST("api/coordinates") - Observable postCoordinate(@Field("latitude") Double latitude); -*/ @PUT("api/coordinates/{id}") - Call putCoordinatesById(@Path("id") String id); + Single putCoordinatesById(@Path("id") String id); @DELETE("api/coordinates/{id}") - Call deleteCoordinatesById(@Path("id") String id); + Single deleteCoordinatesById(@Path("id") String id); } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationRequestHelper.java b/app/src/main/java/com/uam/wmi/findmytutor/service/LocationRequestHelper.java deleted file mode 100644 index 3169bfa..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationRequestHelper.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.uam.wmi.findmytutor.service; - -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import android.content.Context; -import android.preference.PreferenceManager; - - -public class LocationRequestHelper { - - public final static String KEY_LOCATION_UPDATES_REQUESTED = "location-updates-requested"; - - public static void setRequesting(Context context, boolean value) { - PreferenceManager.getDefaultSharedPreferences(context) - .edit() - .putBoolean(KEY_LOCATION_UPDATES_REQUESTED, value) - .apply(); - } - - public static boolean getRequesting(Context context) { - return PreferenceManager.getDefaultSharedPreferences(context) - .getBoolean(KEY_LOCATION_UPDATES_REQUESTED, false); - } -} diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationResultHelper.java b/app/src/main/java/com/uam/wmi/findmytutor/service/LocationResultHelper.java deleted file mode 100644 index 70ee270..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationResultHelper.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.uam.wmi.findmytutor.service; - -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.location.Location; -import android.os.Build; -import android.preference.PreferenceManager; -import android.support.annotation.RequiresApi; -import android.support.v4.app.NotificationCompat; -import android.support.v4.app.TaskStackBuilder; -import android.app.NotificationChannel; - - -import com.uam.wmi.findmytutor.R; -import com.uam.wmi.findmytutor.activity.MainActivity; - -import java.text.DateFormat; -import java.util.Date; -import java.util.List; - -/** - * Class to process location results. - */ -public class LocationResultHelper { - - public final static String KEY_LOCATION_UPDATES_RESULT = "location-update-result"; - - final private static String PRIMARY_CHANNEL = "default"; - - - private Context mContext; - private List mLocations; - private NotificationManager mNotificationManager; - - @RequiresApi(api = Build.VERSION_CODES.O) - LocationResultHelper(Context context, List locations) { - mContext = context; - mLocations = locations; - - NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, - context.getString(R.string.default_channel), NotificationManager.IMPORTANCE_DEFAULT); - channel.setLightColor(Color.GREEN); - channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); - getNotificationManager().createNotificationChannel(channel); - } - - /** - * Returns the title for reporting about a list of {@link Location} objects. - */ - private String getLocationResultTitle() { - String numLocationsReported = mContext.getResources().getQuantityString( - R.plurals.num_locations_reported, mLocations.size(), mLocations.size()); - return numLocationsReported + ": " + DateFormat.getDateTimeInstance().format(new Date()); - } - - private String getLocationResultText() { - if (mLocations.isEmpty()) { - return mContext.getString(R.string.unknown_location); - } - StringBuilder sb = new StringBuilder(); - for (Location location : mLocations) { - sb.append("("); - sb.append(location.getLatitude()); - sb.append(", "); - sb.append(location.getLongitude()); - sb.append(")"); - sb.append("\n"); - } - return sb.toString(); - } - - /** - * Saves location result as a string to {@link android.content.SharedPreferences}. - */ - void saveResults() { - PreferenceManager.getDefaultSharedPreferences(mContext) - .edit() - .putString(KEY_LOCATION_UPDATES_RESULT, getLocationResultTitle() + "\n" + - getLocationResultText()) - .apply(); - } - - /** - * Fetches location results from {@link android.content.SharedPreferences}. - */ - public static String getSavedLocationResult(Context context) { - return PreferenceManager.getDefaultSharedPreferences(context) - .getString(KEY_LOCATION_UPDATES_RESULT, ""); - } - - /** - * Get the notification mNotificationManager. - *

- * Utility method as this helper works with it a lot. - * - * @return The system service NotificationManager - */ - private NotificationManager getNotificationManager() { - if (mNotificationManager == null) { - mNotificationManager = (NotificationManager) mContext.getSystemService( - Context.NOTIFICATION_SERVICE); - } - return mNotificationManager; - } - - /** - * Displays a notification with the location results. - */ - void showNotification() { - Intent notificationIntent = new Intent(mContext, MainActivity.class); - - // Construct a task stack. - TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext); - - // Add the main Activity to the task stack as the parent. - stackBuilder.addParentStack(MainActivity.class); - - // Push the content Intent onto the stack. - stackBuilder.addNextIntent(notificationIntent); - - // Get a PendingIntent containing the entire back stack. - PendingIntent notificationPendingIntent = - stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - - Notification.Builder notificationBuilder = null; - - notificationBuilder = new Notification.Builder(mContext, - PRIMARY_CHANNEL) - .setContentTitle(getLocationResultTitle()) - .setContentText(getLocationResultText()) - .setSmallIcon(R.mipmap.ic_launcher) - .setAutoCancel(true) - .setContentIntent(notificationPendingIntent); - - getNotificationManager().notify(0, notificationBuilder.build()); - } -} diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/LocationService.java deleted file mode 100644 index ecbd540..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/LocationService.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.uam.wmi.findmytutor.service; - -import android.Manifest; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.IBinder; -import android.support.v4.app.ActivityCompat; -import android.util.Log; -import android.widget.Toast; - -public class LocationService extends Service { - public static final String BROADCAST_ACTION = "Hello World"; - private static final int TWO_MINUTES = 1000 * 60 * 2; - public LocationManager locationManager; - public MyLocationListener listener; - public Location previousBestLocation = null; - - Intent intent; - int counter = 0; - - @Override - public void onCreate() { - super.onCreate(); - intent = new Intent(BROADCAST_ACTION); - - locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); - listener = new MyLocationListener(); - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. - return; - } - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener); - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener); - } - - - @Override - public IBinder onBind(Intent intent) - { - return null; - } - - protected boolean isBetterLocation(Location location, Location currentBestLocation) { - if (currentBestLocation == null) { - // A new location is always better than no location - return true; - } - - // Check whether the new location fix is newer or older - long timeDelta = location.getTime() - currentBestLocation.getTime(); - boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; - boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; - boolean isNewer = timeDelta > 0; - - // If it's been more than two minutes since the current location, use the new location - // because the user has likely moved - if (isSignificantlyNewer) { - return true; - // If the new location is more than two minutes older, it must be worse - } else if (isSignificantlyOlder) { - return false; - } - - // Check whether the new location fix is more or less accurate - int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); - boolean isLessAccurate = accuracyDelta > 0; - boolean isMoreAccurate = accuracyDelta < 0; - boolean isSignificantlyLessAccurate = accuracyDelta > 200; - - // Check if the old and new location are from the same provider - boolean isFromSameProvider = isSameProvider(location.getProvider(), - currentBestLocation.getProvider()); - - // Determine location quality using a combination of timeliness and accuracy - if (isMoreAccurate) { - return true; - } else if (isNewer && !isLessAccurate) { - return true; - } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { - return true; - } - return false; - } - - - - /** Checks whether two providers are the same */ - private boolean isSameProvider(String provider1, String provider2) { - if (provider1 == null) { - return provider2 == null; - } - return provider1.equals(provider2); - } - - - - @Override - public void onDestroy() { - // handler.removeCallbacks(sendUpdatesToUI); - super.onDestroy(); - Log.v("STOP_SERVICE", "DONE"); - locationManager.removeUpdates((LocationListener) listener); - } - - public static Thread performOnBackgroundThread(final Runnable runnable) { - final Thread t = new Thread() { - @Override - public void run() { - try { - runnable.run(); - } finally { - - } - } - }; - t.start(); - return t; - } - - - - - public class MyLocationListener implements LocationListener - { - - public void onLocationChanged(final Location loc) - { - Log.i("*******", "Location changed"); - if(isBetterLocation(loc, previousBestLocation)) { - loc.getLatitude(); - loc.getLongitude(); - - Log.e("service", String.valueOf(loc)); - intent.putExtra("Latitude", loc.getLatitude()); - intent.putExtra("Longitude", loc.getLongitude()); - intent.putExtra("Provider", loc.getProvider()); - sendBroadcast(intent); - - } - } - - - public void onProviderDisabled(String provider) - { - Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show(); - } - - - public void onProviderEnabled(String provider) - { - Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); - } - - - public void onStatusChanged(String provider, int status, Bundle extras) - { - - } - - } -} \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java index 51d5d7a..527a11c 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java @@ -41,11 +41,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent intent) { - Double latitude, longitude; - latitude = intent.getDoubleExtra("latitude", 0); - - Log.e("Background service", String.valueOf(latitude)); - final PendingResult pendingResult = goAsync(); Task asyncTask = new Task(pendingResult, intent); asyncTask.execute(); @@ -55,24 +50,31 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { private final PendingResult pendingResult; private final Intent intent; + private Double latitude; + private Double longitude; + private CompositeDisposable disposable = new CompositeDisposable(); private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) - .create(CoordinateService .class); + .create(CoordinateService.class); private Task(PendingResult pendingResult, Intent intent) { this.pendingResult = pendingResult; this.intent = intent; this.latitude = intent.getDoubleExtra("latitude", 0); + this.longitude = intent.getDoubleExtra("longitude", 0); } @Override protected Object doInBackground(Object[] objects) { - //Here you can obtain value from receiver - Log.e("task", String.valueOf(this.latitude)); - Coordinate coordinate = new Coordinate(52.467099,16.927560, "android",PrefUtils.getUserId(getApplicationContext())); + Coordinate coordinate = new Coordinate( + this.latitude, + this.longitude, + "android", + PrefUtils.getUserId(getApplicationContext()) + ); disposable.add( coordinateService @@ -95,8 +97,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { return null; } - - } } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/MyDividerItemDecoration.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/MyDividerItemDecoration.java deleted file mode 100644 index 96a4d62..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/MyDividerItemDecoration.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.uam.wmi.findmytutor.utils; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; -import android.util.TypedValue; -import android.view.View; - -public class MyDividerItemDecoration extends RecyclerView.ItemDecoration { - - private static final int[] ATTRS = new int[]{ - android.R.attr.listDivider - }; - - public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; - public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; - - private Drawable mDivider; - private int mOrientation; - private Context context; - private int margin; - - public MyDividerItemDecoration(Context context, int orientation, int margin) { - this.context = context; - this.margin = margin; - final TypedArray a = context.obtainStyledAttributes(ATTRS); - mDivider = a.getDrawable(0); - a.recycle(); - setOrientation(orientation); - } - - public void setOrientation(int orientation) { - if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { - throw new IllegalArgumentException("invalid orientation"); - } - mOrientation = orientation; - } - - @Override - public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { - if (mOrientation == VERTICAL_LIST) { - drawVertical(c, parent); - } else { - drawHorizontal(c, parent); - } - } - - public void drawVertical(Canvas c, RecyclerView parent) { - final int left = parent.getPaddingLeft(); - final int right = parent.getWidth() - parent.getPaddingRight(); - - final int childCount = parent.getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = parent.getChildAt(i); - final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child - .getLayoutParams(); - final int top = child.getBottom() + params.bottomMargin; - final int bottom = top + mDivider.getIntrinsicHeight(); - mDivider.setBounds(left + dpToPx(margin), top, right - dpToPx(margin), bottom); - mDivider.draw(c); - } - } - - public void drawHorizontal(Canvas c, RecyclerView parent) { - final int top = parent.getPaddingTop(); - final int bottom = parent.getHeight() - parent.getPaddingBottom(); - - final int childCount = parent.getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = parent.getChildAt(i); - final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child - .getLayoutParams(); - final int left = child.getRight() + params.rightMargin; - final int right = left + mDivider.getIntrinsicHeight(); - mDivider.setBounds(left, top + dpToPx(margin), right, bottom - dpToPx(margin)); - mDivider.draw(c); - } - } - - @Override - public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { - if (mOrientation == VERTICAL_LIST) { - outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); - } else { - outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); - } - } - - private int dpToPx(int dp) { - Resources r = context.getResources(); - return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics())); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/RecyclerTouchListener.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/RecyclerTouchListener.java deleted file mode 100644 index 28aef5d..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/RecyclerTouchListener.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.uam.wmi.findmytutor.utils; - -import android.content.Context; -import android.support.v7.widget.RecyclerView; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; - -public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { - - private ClickListener clicklistener; - private GestureDetector gestureDetector; - - public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener) { - - this.clicklistener = clicklistener; - gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { - @Override - public boolean onSingleTapUp(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - View child = recycleView.findChildViewUnder(e.getX(), e.getY()); - if (child != null && clicklistener != null) { - clicklistener.onLongClick(child, recycleView.getChildAdapterPosition(child)); - } - } - }); - } - - @Override - public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { - View child = rv.findChildViewUnder(e.getX(), e.getY()); - if (child != null && clicklistener != null && gestureDetector.onTouchEvent(e)) { - clicklistener.onClick(child, rv.getChildAdapterPosition(child)); - } - return false; - } - - @Override - public void onTouchEvent(RecyclerView rv, MotionEvent e) { - } - - @Override - public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { - } - - public interface ClickListener { - void onClick(View view, int position); - void onLongClick(View view, int position); - } -} \ No newline at end of file From 182e3e473e48046200ec4a0bc047a3386e258f18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mieszko=20Wrzeszczy=C5=84ski?= Date: Sat, 6 Oct 2018 20:12:07 +0200 Subject: [PATCH 2/2] Kill backgrund task on logout --- .../findmytutor/activity/LoginActivity.java | 1 + .../findmytutor/activity/MainActivity.java | 68 +++--- .../findmytutor/activity/StartupActivity.java | 12 +- .../uam/wmi/findmytutor/model/Coordinate.java | 8 + .../service/ApplicationServiceWatcher.java | 41 ---- .../BackgroundLocalizationService.java | 212 ++++++++++-------- .../service/CoordinateService.java | 1 - .../utils/BroadcastLocalizationHandler.java | 56 ++--- .../uam/wmi/findmytutor/utils/PrefUtils.java | 33 +-- 9 files changed, 217 insertions(+), 215 deletions(-) delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/service/ApplicationServiceWatcher.java diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java index 0c2dbc5..a113c6f 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java @@ -358,6 +358,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< JWT jwt = new JWT(token); Claim role = jwt.getClaim("nameid"); + PrefUtils.isLoggedIn(getApplicationContext(), true); PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeUserId(getApplicationContext(), role.asString()); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java index c69849b..6d36c71 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java @@ -1,22 +1,23 @@ package com.uam.wmi.findmytutor.activity; import android.content.BroadcastReceiver; -import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; +import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; +import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; + import android.support.design.widget.FloatingActionButton; import android.app.Fragment; @@ -39,7 +40,7 @@ public class MainActivity extends AppCompatActivity { private MapFragment mapFragment; private NotificationFragment notificationFragment; private ProfileFragment profileFragment; - public static Intent backgroundLocalizationService = null; + public static IntentFilter backgroundLocalizationService = null; private BroadcastReceiver broadcastReceiver = null; @@ -91,27 +92,22 @@ public class MainActivity extends AppCompatActivity { // Logout button final FloatingActionButton button = findViewById(R.id.logoutButton); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - PrefUtils.storeIsServiceRunning(getApplicationContext(), false); + button.setOnClickListener(view -> { + PrefUtils.cleanUserLocalStorage(getApplicationContext()); + unRegisterLocalizationService(); - //stopService(MainActivity.backgroundLocalizationService); - SharedPreferences preferences = getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.clear().commit(); + Intent i = getBaseContext().getPackageManager() + .getLaunchIntentForPackage(getBaseContext().getPackageName()); + i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); + finish(); + startActivity(i); - Intent i = getBaseContext().getPackageManager() - .getLaunchIntentForPackage(getBaseContext().getPackageName()); - i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(i); - finish(); - } }); - - fn_permission(); - this.broadcastReceiver = new BroadcastLocalizationHandler(); + if (isTutor) { + fn_permission(); + this.broadcastReceiver = new BroadcastLocalizationHandler(); + } } private void setFragment(Fragment fragment) { @@ -134,15 +130,12 @@ public class MainActivity extends AppCompatActivity { } else { boolean_permission = true; if (boolean_permission) { - if (!PrefUtils.getIsServiceRunning(getApplicationContext())) { + if (!PrefUtils.isLoggedIn(getApplicationContext())) { Intent intent = new Intent(getApplicationContext(), BackgroundLocalizationService.class); startService(intent); - } else { - Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show(); - } } } @@ -166,13 +159,36 @@ public class MainActivity extends AppCompatActivity { @Override protected void onResume() { super.onResume(); - registerReceiver(this.broadcastReceiver, new IntentFilter(BackgroundLocalizationService.str_receiver)); + backgroundLocalizationService = new IntentFilter(BackgroundLocalizationService.str_receiver); + + if (isTutor) + registerReceiver(this.broadcastReceiver, backgroundLocalizationService); } @Override protected void onPause() { super.onPause(); - unregisterReceiver(this.broadcastReceiver); + + if (isTutor) + unregisterReceiver(this.broadcastReceiver); + } + + protected void onDestroy() { + unRegisterLocalizationService(); + super.onDestroy(); + } + + private void unRegisterLocalizationService() { + if (this.broadcastReceiver != null) { + try { + LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver); + + Intent intent = new Intent(this, BackgroundLocalizationService.class); + stopService(intent); + } catch (IllegalArgumentException e) { + Log.d("Destroy app", "RECIEVER UNREGISTER ERROR"); + } + } } } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/StartupActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/StartupActivity.java index 529b024..d72ccb0 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/StartupActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/StartupActivity.java @@ -1,22 +1,20 @@ package com.uam.wmi.findmytutor.activity; import android.app.Activity; -import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; -import com.uam.wmi.findmytutor.service.ApplicationServiceWatcher; +import com.uam.wmi.findmytutor.utils.PrefUtils; public class StartupActivity extends AppCompatActivity { - private static final int AUTHENTICATION_REQUEST_CODE = 666; + private static final int AUTHENTICATION_REQUEST_CODE = 666; @Override protected void onCreate(Bundle savedInstanceState) { - - if (isLoggedIn()){ + if (isLoggedIn()) { Intent startupIntent = new Intent(this, MainActivity.class); startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(startupIntent); @@ -31,11 +29,11 @@ public class StartupActivity extends AppCompatActivity { } private boolean isLoggedIn() { - return this.getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE).getBoolean("loggedIn",false); + return PrefUtils.getIsTutor(getApplicationContext()); } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data){ + protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == AUTHENTICATION_REQUEST_CODE && resultCode == Activity.RESULT_OK) { Intent startupIntent = new Intent(this, MainActivity.class); startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java index 5624324..a83053a 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java @@ -1,5 +1,7 @@ package com.uam.wmi.findmytutor.model; +import android.util.Range; + import com.google.gson.annotations.SerializedName; import java.util.Objects; @@ -12,6 +14,9 @@ import io.swagger.annotations.ApiModelProperty; */ public class Coordinate extends BaseResponse { + Range latitudeRange = Range.create(52.466709, 52.467007); + Range longtitudeRange = Range.create(16.926159, 16.926976); + @SerializedName("coordinateId") private UUID coordinateId = null; @@ -40,6 +45,9 @@ public class Coordinate extends BaseResponse { private String label; public Coordinate (Double latitude, Double longitude, String label, String userId) { + //if (!latitudeRange.contains(latitude)) throw new IllegalArgumentException("Inappropriate latitude value" + latitude); + //if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude); + this.latitude = latitude; this.longitude = longitude; this.userId = userId; diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/ApplicationServiceWatcher.java b/app/src/main/java/com/uam/wmi/findmytutor/service/ApplicationServiceWatcher.java deleted file mode 100644 index 6d7991e..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/ApplicationServiceWatcher.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.uam.wmi.findmytutor.service; - -import android.app.Service; -import android.content.Intent; -import android.os.IBinder; -import android.util.Log; - -import com.uam.wmi.findmytutor.activity.MainActivity; - -import timber.log.Timber; - -public class ApplicationServiceWatcher extends Service { - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - Timber.e("App Started"); - return START_NOT_STICKY; - } - - @Override - public void onDestroy() { - super.onDestroy(); -; - android.os.Process.killProcess(android.os.Process.myPid()); - Timber.e("App destroyed"); - } - - @Override - public void onTaskRemoved(Intent rootIntent) { - Timber.e("App killed"); - android.os.Process.killProcess(android.os.Process.myPid()); - //Code here - stopSelf(); - } -} - diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java index 74e338e..512bde0 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java @@ -1,149 +1,163 @@ package com.uam.wmi.findmytutor.service; -import android.Manifest; import android.app.Service; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; -import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; -import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; - +import android.util.Log; +import android.content.Context; import java.util.Timer; import java.util.TimerTask; -/** - * Created by deepshikha on 24/11/16. - */ +public class BackgroundLocalizationService extends Service { -public class BackgroundLocalizationService extends Service implements LocationListener{ - - - boolean isGPSEnable = false; - boolean isNetworkEnable = false; - double latitude, longitude; - LocationManager locationManager; - Location location; - private Handler mHandler = new Handler(); - private Timer mTimer = null; - long notify_interval = 5000; public static String str_receiver = "background.location.broadcast"; + private static final String TAG = "MyLocationService"; + private LocationManager mLocationManager = null; + private static final int LOCATION_INTERVAL = 10000; + private static final float LOCATION_DISTANCE = 10f; + private Handler mHandler = new Handler(); + private static long notify_interval = 100000; + Location mLastLocation; Intent intent; + private class LocationListener implements android.location.LocationListener { - public BackgroundLocalizationService() {} + public LocationListener(String provider) { + Log.e(TAG, "LocationListener " + provider); + mLastLocation = new Location(provider); + } + + @Override + public void onLocationChanged(Location location) { + Log.e(TAG, "onLocationChanged: " + location); + mLastLocation.set(location); + sendToBroadcast(mLastLocation); + } + + @Override + public void onProviderDisabled(String provider) { + Log.e(TAG, "onProviderDisabled: " + provider); + } + + @Override + public void onProviderEnabled(String provider) { + Log.e(TAG, "onProviderEnabled: " + provider); + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + Log.e(TAG, "onStatusChanged: " + provider); + } + } + + LocationListener[] mLocationListeners = new LocationListener[]{ + new LocationListener(LocationManager.GPS_PROVIDER), + new LocationListener(LocationManager.NETWORK_PROVIDER), + new LocationListener(LocationManager.PASSIVE_PROVIDER) + }; - @Nullable @Override - public IBinder onBind(Intent intent) { + public IBinder onBind(Intent arg0) { return null; } @Override - public void onCreate() { - super.onCreate(); + public int onStartCommand(Intent intent, int flags, int startId) { + Log.e(TAG, "onStartCommand"); + super.onStartCommand(intent, flags, startId); - mTimer = new Timer(); + return START_NOT_STICKY; + } + + @Override + public void onCreate() { + + Log.e(TAG, "onCreate"); + + initializeLocationManager(); + + try { + mLocationManager.requestLocationUpdates( + LocationManager.PASSIVE_PROVIDER, + LOCATION_INTERVAL, + LOCATION_DISTANCE, + mLocationListeners[0] + ); + } catch (java.lang.SecurityException ex) { + Log.i(TAG, "fail to request location update, ignore", ex); + } catch (IllegalArgumentException ex) { + Log.d(TAG, "network provider does not exist, " + ex.getMessage()); + } + + try { + mLocationManager.requestLocationUpdates( + LocationManager.GPS_PROVIDER, + LOCATION_INTERVAL, + LOCATION_DISTANCE, + mLocationListeners[1] + ); + } catch (java.lang.SecurityException ex) { + Log.i(TAG, "fail to request location update, ignore", ex); + } catch (IllegalArgumentException ex) { + Log.d(TAG, "gps provider does not exist " + ex.getMessage()); + } + + Timer mTimer = new Timer(); mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval); intent = new Intent(str_receiver); } - @Override - public void onLocationChanged(Location location) { - fn_getlocation(); - } @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - - } - - @Override - public void onProviderEnabled(String provider) { - - } - - @Override - public void onProviderDisabled(String provider) { - - } - - private void fn_getlocation() { - locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); - isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); - - if (!isGPSEnable && !isNetworkEnable) { - - } else { - - if (isNetworkEnable) { - location = null; - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. - return; - } - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, (LocationListener) this); - if (locationManager != null) { - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. + public void onDestroy() { + Log.e(TAG, "onDestroy"); + super.onDestroy(); + if (mLocationManager != null) { + for (int i = 0; i < mLocationListeners.length; i++) { + try { + if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } - location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - if (location!=null){ - latitude = location.getLatitude(); - longitude = location.getLongitude(); - fn_update(location); - } - } - - } - - - if (isGPSEnable){ - location = null; - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0, (LocationListener) this); - if (locationManager!=null){ - location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if (location!=null){ - latitude = location.getLatitude(); - longitude = location.getLongitude(); - - fn_update(location); - } + mLocationManager.removeUpdates(mLocationListeners[i]); + } catch (Exception ex) { + Log.i(TAG, "fail to remove location listener, ignore", ex); } } } - } - private class TimerTaskToGetLocation extends TimerTask{ + private void initializeLocationManager() { + Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE); + if (mLocationManager == null) { + mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); + } + } + + private class TimerTaskToGetLocation extends TimerTask { @Override public void run() { - mHandler.post(BackgroundLocalizationService.this::fn_getlocation); + mHandler.post(BackgroundLocalizationService.this::getLocation); } } - private void fn_update(Location location){ + private void sendToBroadcast(Location location) { + Log.e("sendToBroadcast", String.valueOf(location)); + intent.putExtra("latitude",location.getLatitude()); intent.putExtra("longitude",location.getLongitude()); sendBroadcast(intent); } + + private void getLocation() { + sendToBroadcast(mLastLocation); + } + + } \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java index 987e666..693c6a3 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/CoordinateService.java @@ -40,7 +40,6 @@ public interface CoordinateService { @GET("api/coordinates/top/online") Single> getOnlineCoordinates(); - //works @POST("api/coordinates") Single postCoordinate(@Body Coordinate coordinate); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java index 527a11c..afd7765 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java @@ -6,6 +6,7 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; +import android.support.v4.content.LocalBroadcastManager; import android.util.ArrayMap; import android.util.Log; @@ -33,6 +34,7 @@ import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; +import timber.log.Timber; import static android.content.ContentValues.TAG; import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext; @@ -47,10 +49,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { } private static class Task extends AsyncTask { - - private final PendingResult pendingResult; - private final Intent intent; - private Double latitude; private Double longitude; @@ -59,8 +57,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { .create(CoordinateService.class); private Task(PendingResult pendingResult, Intent intent) { - this.pendingResult = pendingResult; - this.intent = intent; this.latitude = intent.getDoubleExtra("latitude", 0); this.longitude = intent.getDoubleExtra("longitude", 0); } @@ -69,31 +65,35 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver { @Override protected Object doInBackground(Object[] objects) { - Coordinate coordinate = new Coordinate( - this.latitude, - this.longitude, - "android", - PrefUtils.getUserId(getApplicationContext()) - ); + try { - disposable.add( - coordinateService - .postCoordinate(coordinate) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableSingleObserver() { - @SuppressLint("LongLogTag") - @Override - public void onSuccess(Coordinate coord) { - Log.e("CoordinateService onSuccess", String.valueOf(coord)); + Coordinate coordinate = new Coordinate( + this.latitude, + this.longitude, + PrefUtils.getUserStatus(getApplicationContext()), + PrefUtils.getUserId(getApplicationContext()) + ); - } + disposable.add( + coordinateService + .postCoordinate(coordinate) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith(new DisposableSingleObserver() { + @SuppressLint("LongLogTag") + @Override + public void onSuccess(Coordinate coord) { + Log.e("CoordinateService onSuccess", String.valueOf(coord)); + } - @Override - public void onError(Throwable e) { - Log.e("LoginError", "onError: " + e.getMessage()); - } - })); + @Override + public void onError(Throwable e) { + Log.e("LoginError", "onError: " + e.getMessage()); + } + })); + } catch (IllegalArgumentException e) { + Timber.e(String.valueOf(e)); + } return null; } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java index 54f92a1..ad9f496 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java @@ -8,10 +8,7 @@ import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.JWT; public class PrefUtils { - /** - * Storing API Key in shared preferences to - * add it in header part of every retrofit request - */ + public PrefUtils() { } @@ -22,7 +19,7 @@ public class PrefUtils { public static void storeApiKey(Context context, String apiKey) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putString("API_KEY", apiKey); - editor.commit(); + editor.apply(); } public static String getApiKey(Context context) { @@ -31,32 +28,42 @@ public class PrefUtils { public static void storeUserId(Context applicationContext, String userId) { SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit(); - editor.putString("USER_ID", userId); - editor.commit(); + editor.apply(); } public static String getUserId(Context context) { return getSharedPreferences(context).getString("USER_ID", null); } + + public static String getUserStatus(Context context) { + return getSharedPreferences(context).getString("USER_STATUS", "Android"); + } + public static void storeIsTutor(Context applicationContext, boolean isTutor) { SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit(); editor.putBoolean("IS_TUTOR", isTutor); - editor.commit(); + editor.apply(); } public static boolean getIsTutor(Context context) { return getSharedPreferences(context).getBoolean("IS_TUTOR", false); } - public static void storeIsServiceRunning(Context applicationContext, boolean isRunning) { + public static void isLoggedIn(Context applicationContext, boolean isLogged) { SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit(); - editor.putBoolean("IS_BACKGROUND_SERVICE_RUNNING", isRunning); - editor.commit(); + editor.putBoolean("IS_LOGGED_IN", isLogged); + editor.apply(); } - public static boolean getIsServiceRunning(Context context) { - return getSharedPreferences(context).getBoolean("IS_BACKGROUND_SERVICE_RUNNING", false); + public static boolean isLoggedIn(Context context) { + return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false); + } + + public static void cleanUserLocalStorage(Context context) { + SharedPreferences preferences = getSharedPreferences(context); + SharedPreferences.Editor editor = preferences.edit(); + editor.clear().apply(); } } \ No newline at end of file