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); JWT jwt = new JWT(token);
Claim role = jwt.getClaim("nameid"); Claim role = jwt.getClaim("nameid");
PrefUtils.isLoggedIn(getApplicationContext(), true);
PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeApiKey(getApplicationContext(), token);
PrefUtils.storeUserId(getApplicationContext(), role.asString()); PrefUtils.storeUserId(getApplicationContext(), role.asString());

View File

@ -1,22 +1,23 @@
package com.uam.wmi.findmytutor.activity; package com.uam.wmi.findmytutor.activity;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.support.design.widget.BottomNavigationView; import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.View; import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.Toast; import android.widget.Toast;
import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; import com.uam.wmi.findmytutor.service.BackgroundLocalizationService;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.app.Fragment; import android.app.Fragment;
@ -39,7 +40,7 @@ public class MainActivity extends AppCompatActivity {
private MapFragment mapFragment; private MapFragment mapFragment;
private NotificationFragment notificationFragment; private NotificationFragment notificationFragment;
private ProfileFragment profileFragment; private ProfileFragment profileFragment;
public static Intent backgroundLocalizationService = null; public static IntentFilter backgroundLocalizationService = null;
private BroadcastReceiver broadcastReceiver = null; private BroadcastReceiver broadcastReceiver = null;
@ -91,28 +92,23 @@ public class MainActivity extends AppCompatActivity {
// Logout button // Logout button
final FloatingActionButton button = findViewById(R.id.logoutButton); final FloatingActionButton button = findViewById(R.id.logoutButton);
button.setOnClickListener(new View.OnClickListener() { button.setOnClickListener(view -> {
@Override PrefUtils.cleanUserLocalStorage(getApplicationContext());
public void onClick(View view) { unRegisterLocalizationService();
PrefUtils.storeIsServiceRunning(getApplicationContext(), false);
//stopService(MainActivity.backgroundLocalizationService);
SharedPreferences preferences = getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear().commit();
Intent i = getBaseContext().getPackageManager() Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName()); .getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish(); finish();
} startActivity(i);
}); });
if (isTutor) {
fn_permission(); fn_permission();
this.broadcastReceiver = new BroadcastLocalizationHandler(); this.broadcastReceiver = new BroadcastLocalizationHandler();
} }
}
private void setFragment(Fragment fragment) { private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
@ -134,15 +130,12 @@ public class MainActivity extends AppCompatActivity {
} else { } else {
boolean_permission = true; boolean_permission = true;
if (boolean_permission) { if (boolean_permission) {
if (!PrefUtils.getIsServiceRunning(getApplicationContext())) { if (!PrefUtils.isLoggedIn(getApplicationContext())) {
Intent intent = new Intent(getApplicationContext(), BackgroundLocalizationService.class); Intent intent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
startService(intent); startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
} }
} else { } else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
} }
} }
} }
@ -166,13 +159,36 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
registerReceiver(this.broadcastReceiver, new IntentFilter(BackgroundLocalizationService.str_receiver)); backgroundLocalizationService = new IntentFilter(BackgroundLocalizationService.str_receiver);
if (isTutor)
registerReceiver(this.broadcastReceiver, backgroundLocalizationService);
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
if (isTutor)
unregisterReceiver(this.broadcastReceiver); 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; package com.uam.wmi.findmytutor.activity;
import android.app.Activity; import android.app.Activity;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import com.uam.wmi.findmytutor.service.ApplicationServiceWatcher; import com.uam.wmi.findmytutor.utils.PrefUtils;
public class StartupActivity extends AppCompatActivity { public class StartupActivity extends AppCompatActivity {
@ -15,8 +14,7 @@ public class StartupActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
if (isLoggedIn()) {
if (isLoggedIn()){
Intent startupIntent = new Intent(this, MainActivity.class); Intent startupIntent = new Intent(this, MainActivity.class);
startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startupIntent); startActivity(startupIntent);
@ -31,11 +29,11 @@ public class StartupActivity extends AppCompatActivity {
} }
private boolean isLoggedIn() { private boolean isLoggedIn() {
return this.getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE).getBoolean("loggedIn",false); return PrefUtils.getIsTutor(getApplicationContext());
} }
@Override @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) { if (requestCode == AUTHENTICATION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Intent startupIntent = new Intent(this, MainActivity.class); Intent startupIntent = new Intent(this, MainActivity.class);
startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); 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; package com.uam.wmi.findmytutor.model;
import android.util.Range;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.Objects; import java.util.Objects;
@ -12,6 +14,9 @@ import io.swagger.annotations.ApiModelProperty;
*/ */
public class Coordinate extends BaseResponse { 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") @SerializedName("coordinateId")
private UUID coordinateId = null; private UUID coordinateId = null;
@ -40,6 +45,9 @@ public class Coordinate extends BaseResponse {
private String label; private String label;
public Coordinate (Double latitude, Double longitude, String label, String userId) { 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.latitude = latitude;
this.longitude = longitude; this.longitude = longitude;
this.userId = userId; 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; package com.uam.wmi.findmytutor.service;
import android.Manifest;
import android.app.Service; import android.app.Service;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.location.Location; import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager; import android.location.LocationManager;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.IBinder; import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.content.Context;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
/** public class BackgroundLocalizationService extends Service {
* Created by deepshikha on 24/11/16.
*/
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"; 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; Intent intent;
private class LocationListener implements android.location.LocationListener {
public BackgroundLocalizationService() {} public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
@Nullable mLastLocation = new Location(provider);
@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);
} }
@Override @Override
public void onLocationChanged(Location location) { public void onLocationChanged(Location location) {
fn_getlocation(); Log.e(TAG, "onLocationChanged: " + location);
} mLastLocation.set(location);
sendToBroadcast(mLastLocation);
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
} }
@Override @Override
public void onProviderDisabled(String provider) { public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
} }
private void fn_getlocation() { @Override
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); public void onProviderEnabled(String provider) {
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); Log.e(TAG, "onProviderEnabled: " + provider);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_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) { @Override
location = null; public IBinder onBind(Intent arg0) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return null;
// TODO: Consider calling }
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding @Override
// public void onRequestPermissionsResult(int requestCode, String[] permissions, public int onStartCommand(Intent intent, int flags, int startId) {
// int[] grantResults) Log.e(TAG, "onStartCommand");
// to handle the case where the user grants the permission. See the documentation super.onStartCommand(intent, flags, startId);
// for ActivityCompat#requestPermissions for more details.
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; return;
} }
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, (LocationListener) this); mLocationManager.removeUpdates(mLocationListeners[i]);
if (locationManager != null) { } catch (Exception ex) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "fail to remove location listener, ignore", ex);
// 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);
} }
} }
} }
} }
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 @Override
public void run() { 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("latitude",location.getLatitude());
intent.putExtra("longitude",location.getLongitude()); intent.putExtra("longitude",location.getLongitude());
sendBroadcast(intent); sendBroadcast(intent);
} }
private void getLocation() {
sendToBroadcast(mLastLocation);
}
} }

View File

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

View File

@ -6,6 +6,7 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.support.v4.content.LocalBroadcastManager;
import android.util.ArrayMap; import android.util.ArrayMap;
import android.util.Log; import android.util.Log;
@ -33,6 +34,7 @@ import okhttp3.RequestBody;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import timber.log.Timber;
import static android.content.ContentValues.TAG; import static android.content.ContentValues.TAG;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext; import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
@ -47,10 +49,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
} }
private static class Task extends AsyncTask { private static class Task extends AsyncTask {
private final PendingResult pendingResult;
private final Intent intent;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
@ -59,8 +57,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
.create(CoordinateService.class); .create(CoordinateService.class);
private Task(PendingResult pendingResult, Intent intent) { private Task(PendingResult pendingResult, Intent intent) {
this.pendingResult = pendingResult;
this.intent = intent;
this.latitude = intent.getDoubleExtra("latitude", 0); this.latitude = intent.getDoubleExtra("latitude", 0);
this.longitude = intent.getDoubleExtra("longitude", 0); this.longitude = intent.getDoubleExtra("longitude", 0);
} }
@ -69,10 +65,12 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override @Override
protected Object doInBackground(Object[] objects) { protected Object doInBackground(Object[] objects) {
try {
Coordinate coordinate = new Coordinate( Coordinate coordinate = new Coordinate(
this.latitude, this.latitude,
this.longitude, this.longitude,
"android", PrefUtils.getUserStatus(getApplicationContext()),
PrefUtils.getUserId(getApplicationContext()) PrefUtils.getUserId(getApplicationContext())
); );
@ -86,7 +84,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override @Override
public void onSuccess(Coordinate coord) { public void onSuccess(Coordinate coord) {
Log.e("CoordinateService onSuccess", String.valueOf(coord)); Log.e("CoordinateService onSuccess", String.valueOf(coord));
} }
@Override @Override
@ -94,6 +91,9 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
Log.e("LoginError", "onError: " + e.getMessage()); Log.e("LoginError", "onError: " + e.getMessage());
} }
})); }));
} catch (IllegalArgumentException e) {
Timber.e(String.valueOf(e));
}
return null; return null;
} }

View File

@ -8,10 +8,7 @@ import com.auth0.android.jwt.Claim;
import com.auth0.android.jwt.JWT; import com.auth0.android.jwt.JWT;
public class PrefUtils { public class PrefUtils {
/**
* Storing API Key in shared preferences to
* add it in header part of every retrofit request
*/
public PrefUtils() { public PrefUtils() {
} }
@ -22,7 +19,7 @@ public class PrefUtils {
public static void storeApiKey(Context context, String apiKey) { public static void storeApiKey(Context context, String apiKey) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit(); SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString("API_KEY", apiKey); editor.putString("API_KEY", apiKey);
editor.commit(); editor.apply();
} }
public static String getApiKey(Context context) { public static String getApiKey(Context context) {
@ -31,32 +28,42 @@ public class PrefUtils {
public static void storeUserId(Context applicationContext, String userId) { public static void storeUserId(Context applicationContext, String userId) {
SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit(); SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit();
editor.putString("USER_ID", userId); editor.putString("USER_ID", userId);
editor.commit(); editor.apply();
} }
public static String getUserId(Context context) { public static String getUserId(Context context) {
return getSharedPreferences(context).getString("USER_ID", null); 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) { public static void storeIsTutor(Context applicationContext, boolean isTutor) {
SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit(); SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit();
editor.putBoolean("IS_TUTOR", isTutor); editor.putBoolean("IS_TUTOR", isTutor);
editor.commit(); editor.apply();
} }
public static boolean getIsTutor(Context context) { public static boolean getIsTutor(Context context) {
return getSharedPreferences(context).getBoolean("IS_TUTOR", false); 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(); SharedPreferences.Editor editor = getSharedPreferences(applicationContext).edit();
editor.putBoolean("IS_BACKGROUND_SERVICE_RUNNING", isRunning); editor.putBoolean("IS_LOGGED_IN", isLogged);
editor.commit(); editor.apply();
} }
public static boolean getIsServiceRunning(Context context) { public static boolean isLoggedIn(Context context) {
return getSharedPreferences(context).getBoolean("IS_BACKGROUND_SERVICE_RUNNING", false); 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();
} }
} }