Skip to content

Commit

Permalink
location service refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
aykuttasil committed Dec 18, 2016
1 parent bbe21fc commit a8c9e50
Show file tree
Hide file tree
Showing 10 changed files with 204 additions and 45 deletions.
6 changes: 3 additions & 3 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ android {
applicationId "com.aykuttasil.sweetloc"
minSdkVersion project.minSdk
targetSdkVersion project.sdk
versionCode 5
versionName "1.0.4"
versionCode 6
versionName "1.0.5"
multiDexEnabled true

manifestPlaceholders = [onesignal_app_id : "283c0725-f1ae-434a-8ea5-09f61b1246fc",
Expand Down Expand Up @@ -124,7 +124,7 @@ dependencies {



compile('com.crashlytics.sdk.android:crashlytics:2.6.1@aar') {
compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
transitive = true;
}
apt "org.androidannotations:androidannotations:$AAVersion"
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
package="com.aykuttasil.sweetloc">


<uses-permission
android:name="android.permission.READ_PHONE_STATE"
tools:node="remove" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ public void onCancel() {
@Override
public void onError(FacebookException error) {
Logger.e(error, "facebook:onError");
SuperHelper.CrashlyticsError(error);
}
});
}
Expand Down Expand Up @@ -156,6 +157,8 @@ public void onComplete(@NonNull Task<AuthResult> task) {
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {

SuperHelper.CrashlyticsError(task.getException());

Logger.e(task.getException(), "HATA");

Toast.makeText(LoginFacebookActivity.this, "Authentication failed.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public Observable<String> call(String userId) {
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
goFragment();
});
}, SuperHelper::CrashlyticsError);
} else {
goFragment();
}
Expand All @@ -114,6 +114,7 @@ public Observable<String> call(String userId) {

@DebugLog
private void goFragment() {

SuperHelper.ReplaceFragmentBeginTransaction(
MainActivity.this,
UserTrackerListFragment_.builder().build(),
Expand All @@ -133,12 +134,14 @@ private void goFragment() {
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);

updateUi();
}

@DebugLog
@OnActivityResult(LOGIN_REQUEST_CODE)
public void ActivityResultLogin(int resultCode) {

switch (resultCode) {
case RESULT_OK: {
updateUi();
Expand All @@ -149,6 +152,7 @@ public void ActivityResultLogin(int resultCode) {

@Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu_mainactivity, menu);
return super.onCreateOptionsMenu(menu);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.aykuttasil.androidbasichelperlib.UiHelper;
import com.aykuttasil.sweetloc.BuildConfig;
import com.aykuttasil.sweetloc.R;
import com.aykuttasil.sweetloc.app.AppSweetLoc;
import com.aykuttasil.sweetloc.app.Const;
import com.aykuttasil.sweetloc.db.DbManager;
import com.aykuttasil.sweetloc.helper.SuperHelper;
Expand All @@ -45,10 +46,8 @@
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.Gson;
import com.onesignal.OneSignal;
import com.orhanobut.logger.Logger;
import com.patloew.rxlocation.RxLocation;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tbruyelle.rxpermissions.RxPermissions;
Expand All @@ -73,6 +72,7 @@
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

@EActivity(R.layout.activity_maps)
public class MapsActivity extends BaseActivity implements OnMapReadyCallback, GoogleMap.InfoWindowAdapter, GoogleMap.OnInfoWindowClickListener {
Expand Down Expand Up @@ -100,6 +100,7 @@ public class MapsActivity extends BaseActivity implements OnMapReadyCallback, Go
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mCompositeDisposible = new CompositeDisposable();
}

Expand Down Expand Up @@ -185,10 +186,8 @@ public void onMapReady(GoogleMap googleMap) {
@DebugLog
private void initLocationListener() {

RxLocation rxLocation = new RxLocation(this);

LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(30000)
.setFastestInterval(5000);

Expand All @@ -198,7 +197,7 @@ private void initLocationListener() {
.build();


Disposable disposable = rxLocation.settings().checkAndHandleResolution(locationSettingsRequest)
Disposable disposable = ((AppSweetLoc) getApplication()).rxLocation.settings().checkAndHandleResolution(locationSettingsRequest)
.flatMapObservable(new Function<Boolean, ObservableSource<Location>>() {
@DebugLog
@Override
Expand All @@ -210,16 +209,22 @@ public ObservableSource<Location> apply(Boolean granted) throws Exception {
}

if (granted) {
return rxLocation.location().updates(locationRequest);
return ((AppSweetLoc) getApplication()).rxLocation.location().updates(locationRequest);
} else {
return Observable.error(new Exception("GPS ayarlarında hata var."));
}
}
})
.retry()
.subscribe(location -> {
SuperHelper.sendLocationInformation(location);
});
.retry() // Eğer onError çalışırsa tekrar subscribe olunuyor
.subscribeOn(Schedulers.io())
.subscribe(
SuperHelper::sendLocationInformation,
error -> {
Logger.e(error, "HATA");
SuperHelper.CrashlyticsError(error);
}

);

mCompositeDisposible.add(disposable);

Expand Down Expand Up @@ -261,9 +266,7 @@ private void setMap() {

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

Logger.i(s);
Logger.i(new Gson().toJson(dataSnapshot.getValue()));
//Logger.i(new Gson().toJson(dataSnapshot.getValue()));

ModelLocation modelLocation = dataSnapshot.getValue(ModelLocation.class);

Expand Down Expand Up @@ -427,6 +430,7 @@ public View getInfoContents(Marker marker) {


} catch (Exception e) {
SuperHelper.CrashlyticsError(e);
e.printStackTrace();
}
return vi;
Expand All @@ -435,6 +439,7 @@ public View getInfoContents(Marker marker) {
@DebugLog
@Override
public void onInfoWindowClick(Marker marker) {

LatLng markerLatLng = marker.getPosition();
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng, 15.0f));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.onesignal.OneSignal;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.patloew.rxlocation.RxLocation;

import hugo.weaving.DebugLog;
import io.fabric.sdk.android.Fabric;
Expand All @@ -28,6 +29,8 @@
*/
public class AppSweetLoc extends Application {

public RxLocation rxLocation;

@Override
public void onCreate() {
super.onCreate();
Expand Down Expand Up @@ -70,9 +73,9 @@ public void initSweetLoc() {
.init();

FacebookSdk.sdkInitialize(getApplicationContext());

AppEventsLogger.activateApp(this);

rxLocation = new RxLocation(this);

}

Expand Down
26 changes: 26 additions & 0 deletions app/src/main/java/com/aykuttasil/sweetloc/helper/SuperHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.aykuttasil.sweetloc.model.ModelLocation;
import com.aykuttasil.sweetloc.model.ModelUser;
import com.aykuttasil.sweetloc.receiver.SingleLocationRequestReceiver;
import com.crashlytics.android.Crashlytics;
import com.facebook.login.LoginManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
Expand Down Expand Up @@ -111,4 +112,29 @@ public static void stopPeriodicTask(Context context) {
alarmManager.cancel(pendingIntent);
}

@DebugLog
public static void CrashlyticsError(Throwable error) {

if (DbManager.getModelUser() != null && DbManager.getModelUser().getEmail() != null) {
Crashlytics.setUserEmail(DbManager.getModelUser().getEmail());
Crashlytics.logException(error);
} else {
Crashlytics.logException(error);
}

}

@DebugLog
public static void CrashlyticsLog(String log) {

if (DbManager.getModelUser() != null && DbManager.getModelUser().getEmail() != null) {
Crashlytics.setUserEmail(DbManager.getModelUser().getEmail());
Crashlytics.log(log);
} else {
Crashlytics.log(log);
}

}


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

import com.aykuttasil.sweetloc.service.SingleLocationRequestService;
import com.aykuttasil.sweetloc.util.MyWakefulBroadcastReceiver;

import hugo.weaving.DebugLog;

/**
* Created by aykutasil on 14.12.2016.
*/

public class SingleLocationRequestReceiver extends WakefulBroadcastReceiver {
public class SingleLocationRequestReceiver extends MyWakefulBroadcastReceiver {

@DebugLog
@Override
public void onReceive(Context context, Intent intent) {
Intent intent_ = new Intent(context, SingleLocationRequestService.class);
SingleLocationRequestReceiver.startWakefulService(context, intent_);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;

import com.aykuttasil.sweetloc.app.AppSweetLoc;
import com.aykuttasil.sweetloc.receiver.SingleLocationRequestReceiver;
import com.google.android.gms.location.LocationRequest;
import com.orhanobut.logger.Logger;
import com.patloew.rxlocation.RxLocation;

import java.util.concurrent.TimeUnit;

import hugo.weaving.DebugLog;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

import static com.aykuttasil.sweetloc.helper.SuperHelper.sendLocationInformation;

Expand All @@ -26,6 +25,9 @@

public class SingleLocationRequestService extends IntentService {


// Konum belirlenip yollanabilmesi için max beklenecek zaman
private static long LOCATION_TIMEOUT_IN_SECONDS = 45;
Disposable mDisposable;

@DebugLog
Expand All @@ -37,32 +39,36 @@ public SingleLocationRequestService() {
@Override
protected void onHandleIntent(Intent intent) {

RxLocation rxLocation = new RxLocation(this);

LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(50000)
.setFastestInterval(5000);
if (mDisposable != null && !mDisposable.isDisposed()) {
Logger.i("RxLocation disposed");
mDisposable.dispose();
}

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Logger.i("Permission is not granted");
return;
}

mDisposable = rxLocation.location()

LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(5000)
//.setNumUpdates(1) // Sadece belirttiğimiz miktar kadar (1) location güncellemesi alır
//.setExpirationTime() // gerçek zaman vererek location güncellemesi kontrolü yapılabilir. (gereksiz)
//.setMaxWaitTime() // her bir location güncellemesi için max bekleme süresini belirtebiliriz. setInterval ile ilişkilidir. dikkat et.
.setExpirationDuration(TimeUnit.SECONDS.toMillis(LOCATION_TIMEOUT_IN_SECONDS)); // Belirttiğimiz süre kadar location güncellemesi alır

mDisposable = ((AppSweetLoc) getApplication()).rxLocation.location()
.updates(locationRequest)
.flatMap(new Function<Location, ObservableSource<Location>>() {
@DebugLog
@Override
public ObservableSource<Location> apply(Location location) throws Exception {
if (location.getAccuracy() < 200) {
return Observable.just(location);
} else {
return Observable.error(new Exception("Accuracy > 300"));
}
}
.filter(location -> {

Logger.i("Accuracy: " + location.getAccuracy());

return location.getAccuracy() < 150;

})
.retry()
.timeout(LOCATION_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS, Observable.error(new Exception("Konum sapması çok yüksek.")))
.subscribe(location -> {

sendLocationInformation(location);
Expand All @@ -72,11 +78,13 @@ public ObservableSource<Location> apply(Location location) throws Exception {
SingleLocationRequestReceiver.completeWakefulIntent(intent);

}, error -> {

mDisposable.dispose();

Logger.e(error, "HATA");
});
}


}

@DebugLog
@Override
Expand Down
Loading

0 comments on commit a8c9e50

Please sign in to comment.