Rollback to the first attempt with GoogleService

This commit is contained in:
Mieszko Wrzeszczyński 2018-10-07 15:51:37 +02:00
parent 35af6aa70e
commit 72252ebf87
4 changed files with 361 additions and 80 deletions

View File

@ -1,4 +1,6 @@
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.Context;
@ -71,9 +73,11 @@ public class MainActivity extends AppCompatActivity {
Double latitude, longitude; Double latitude, longitude;
/* CompositeDisposable disposable = new CompositeDisposable(); */
/* CompositeDisposable disposable = new CompositeDisposable();
CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) CoordinateService coordinateService = ApiClient.getClient(getApplicationContext())
.create(CoordinateService.class);*/ .create(CoordinateService.class);*//*
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -215,3 +219,198 @@ public class MainActivity extends AppCompatActivity {
} }
} }
*/
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
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 android.support.design.widget.FloatingActionButton;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.support.annotation.NonNull;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.Mapbox;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.service.GoogleService;
import com.uam.wmi.findmytutor.utils.BroadcastLocalizationHandler;
import com.uam.wmi.findmytutor.utils.PrefUtils;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView mMainNav;
private FrameLayout mMainFrame;
private boolean isTutor;
private MapFragment mapFragment;
private NotificationFragment notificationFragment;
private ProfileFragment profileFragment;
public static IntentFilter backgroundLocalizationService = null;
private BroadcastReceiver broadcastReceiver = null;
private static final int REQUEST_PERMISSIONS = 100;
private boolean boolean_permission = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMainNav = (BottomNavigationView) findViewById(R.id.main_nav);
isTutor = PrefUtils.getIsTutor(getApplicationContext());
if (!isTutor) {
mMainNav.findViewById(R.id.nav_profile).setVisibility(View.GONE);
}
mapFragment = new MapFragment();
notificationFragment = new NotificationFragment();
profileFragment = new ProfileFragment();
// Default frag here
setFragment(mapFragment);
mMainNav.setSelectedItemId(R.id.nav_map);
mMainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_map:
setFragment(mapFragment);
return true;
case R.id.nav_notif:
setFragment(notificationFragment);
return true;
case R.id.nav_profile:
setFragment(profileFragment);
return true;
default:
return false;
}
}
});
// Logout button
final FloatingActionButton button = findViewById(R.id.logoutButton);
button.setOnClickListener(view -> {
PrefUtils.cleanUserLocalStorage(getApplicationContext());
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
unRegisterLocalizationService();
startActivity(i);
});
if (isTutor) {
fn_permission();
this.broadcastReceiver = new BroadcastLocalizationHandler();
}
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
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 && isTutor) {
if (!PrefUtils.isLoggedIn(getApplicationContext())) {
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
@Override
protected void onResume() {
super.onResume();
backgroundLocalizationService = new IntentFilter(GoogleService.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, GoogleService.class);
stopService(intent);
} catch (IllegalArgumentException e) {
Log.d("Destroy app", "RECIEVER UNREGISTER ERROR");
}
}
}
}

View File

@ -1,6 +1,7 @@
package com.uam.wmi.findmytutor.service; package com.uam.wmi.findmytutor.service;
import android.Manifest; import android.Manifest;
import android.app.Notification;
import android.app.Service; import android.app.Service;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -13,6 +14,7 @@ import android.os.Handler;
import android.os.IBinder; import android.os.IBinder;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import android.util.Log; import android.util.Log;
@ -22,11 +24,7 @@ import com.uam.wmi.findmytutor.utils.PrefUtils;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
/** public class GoogleService extends Service {
* Created by deepshikha on 24/11/16.
*/
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false; boolean isGPSEnable = false;
@ -36,12 +34,15 @@ public class GoogleService extends Service implements LocationListener{
Location location; Location location;
private Handler mHandler = new Handler(); private Handler mHandler = new Handler();
private Timer mTimer = null; private Timer mTimer = null;
long notify_interval = 5000; long notify_interval = 50000;
public static String str_receiver = "background.location.broadcast"; public static String str_receiver = "background.location.broadcast";
Intent intent; Intent intent;
Location mLastLocation;
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
public GoogleService() {
public GoogleService() {} }
@Nullable @Nullable
@Override @Override
@ -56,27 +57,57 @@ public class GoogleService extends Service implements LocationListener{
mTimer = new Timer(); mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval); mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver); intent = new Intent(str_receiver);
Notification notification = new NotificationCompat.Builder(this, "NOTIFICATION_CHANNEL")
.setContentText("Content").build();
startForeground(1001, notification);
} }
@Override @Override
public void onLocationChanged(Location location) { public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
} }
@Override private class LocationListener implements android.location.LocationListener {
public void onStatusChanged(String provider, int status, Bundle extras) {
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);
}
} }
@Override LocationListener[] mLocationListeners = new LocationListener[]{
public void onProviderEnabled(String provider) { new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
}
@Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() { private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
@ -87,6 +118,31 @@ public class GoogleService extends Service implements LocationListener{
} else { } else {
if (isGPSEnable) {
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.GPS_PROVIDER, 1000, 0, mLocationListeners[1]);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
if (isNetworkEnable) { if (isNetworkEnable) {
location = null; 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) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
@ -99,7 +155,9 @@ public class GoogleService extends Service implements LocationListener{
// for ActivityCompat#requestPermissions for more details. // for ActivityCompat#requestPermissions for more details.
return; return;
} }
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, (LocationListener) this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListeners[0]);
if (locationManager != null) { 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) { 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 // TODO: Consider calling
@ -122,19 +180,6 @@ public class GoogleService extends Service implements LocationListener{
} }
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);
}
}
}
} }
} }
@ -151,4 +196,34 @@ public class GoogleService extends Service implements LocationListener{
intent.putExtra("longitude",location.getLongitude()); intent.putExtra("longitude",location.getLongitude());
sendBroadcast(intent); sendBroadcast(intent);
} }
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);
}
@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;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
} }

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;
@ -41,62 +43,60 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override @Override
public void onReceive(Context arg0, Intent intent) { 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(); final PendingResult pendingResult = goAsync();
Task asyncTask = new Task(pendingResult, intent); Task asyncTask = new Task(pendingResult, intent);
asyncTask.execute(); asyncTask.execute();
} }
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 CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext())
.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);
} }
@Override @Override
protected Object doInBackground(Object[] objects) { 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())); try {
disposable.add( Coordinate coordinate = new Coordinate(
coordinateService this.latitude,
.postCoordinate(coordinate) this.longitude,
.subscribeOn(Schedulers.io()) PrefUtils.getUserStatus(getApplicationContext()),
.observeOn(AndroidSchedulers.mainThread()) PrefUtils.getUserId(getApplicationContext())
.subscribeWith(new DisposableSingleObserver<Coordinate>() { );
@SuppressLint("LongLogTag")
@Override
public void onSuccess(Coordinate coord) {
Log.e("CoordinateService onSuccess", String.valueOf(coord));
} disposable.add(
coordinateService
.postCoordinate(coordinate)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<Coordinate>() {
@SuppressLint("LongLogTag")
@Override
public void onSuccess(Coordinate coord) {
Log.e("CoordinateService onSuccess", String.valueOf(coord));
}
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
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();
} }
} }