Kill backgrund task on logout

This commit is contained in:
Mieszko Wrzeszczyński 2018-10-06 20:12:07 +02:00
parent 136806adfd
commit 182e3e473e
9 changed files with 217 additions and 215 deletions

View File

@ -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());

View File

@ -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,28 +92,23 @@ 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);
//stopService(MainActivity.backgroundLocalizationService);
SharedPreferences preferences = getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear().commit();
button.setOnClickListener(view -> {
PrefUtils.cleanUserLocalStorage(getApplicationContext());
unRegisterLocalizationService();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
}
startActivity(i);
});
if (isTutor) {
fn_permission();
this.broadcastReceiver = new BroadcastLocalizationHandler();
}
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
@ -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();
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");
}
}
}
}

View File

@ -1,12 +1,11 @@
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 {
@ -15,8 +14,7 @@ public class StartupActivity extends AppCompatActivity {
@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);

View File

@ -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<Double> latitudeRange = Range.create(52.466709, 52.467007);
Range<Double> 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;

View File

@ -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();
}
}

View File

@ -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() {}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
fn_getlocation();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
sendToBroadcast(mLastLocation);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
if (!isGPSEnable && !isNetworkEnable) {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
} else {
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
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.
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
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 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;
}
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.
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 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{
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);
}
}

View File

@ -40,7 +40,6 @@ public interface CoordinateService {
@GET("api/coordinates/top/online")
Single<List<Coordinate>> getOnlineCoordinates();
//works
@POST("api/coordinates")
Single <Coordinate> postCoordinate(@Body Coordinate coordinate);

View File

@ -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,10 +65,12 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override
protected Object doInBackground(Object[] objects) {
try {
Coordinate coordinate = new Coordinate(
this.latitude,
this.longitude,
"android",
PrefUtils.getUserStatus(getApplicationContext()),
PrefUtils.getUserId(getApplicationContext())
);
@ -86,7 +84,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override
public void onSuccess(Coordinate coord) {
Log.e("CoordinateService onSuccess", String.valueOf(coord));
}
@Override
@ -94,6 +91,9 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
Log.e("LoginError", "onError: " + e.getMessage());
}
}));
} catch (IllegalArgumentException e) {
Timber.e(String.valueOf(e));
}
return null;
}

View File

@ -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();
}
}