Run in thread

This commit is contained in:
Mieszko Wrzeszczyński 2018-11-02 23:21:01 +01:00
parent 78957bb62b
commit 05e4de95c2
6 changed files with 117 additions and 129 deletions

View File

@ -9,6 +9,7 @@
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"

View File

@ -53,42 +53,45 @@ public abstract class BaseActivity
setContentView(getContentViewId()); setContentView(getContentViewId());
drawerNavigationView = findViewById(R.id.nav_view); drawerNavigationView = findViewById(R.id.nav_view);
sideDrawer = findViewById(R.id.activity_container); sideDrawer = findViewById(R.id.activity_container);
drawerNavigationView.setNavigationItemSelectedListener( drawerNavigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() { item -> {
@Override String itemName = (String) item.getTitle();
public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent launchIntent;
String itemName = (String) item.getTitle(); if (itemName.equals("Whitelist")) {
Intent launchIntent; /* launchIntent = new Intent(getApplicationContext(), WhitelistActivity.class);
if (itemName.equals("Whitelist")) { startActivity(launchIntent);*/
/* launchIntent = new Intent(getApplicationContext(), WhitelistActivity.class); } else if (itemName.equals("Blacklist")) {
startActivity(launchIntent);*/ /* launchIntent = new Intent(getApplicationContext(), BlacklistActivity.class);
} else if (itemName.equals("Blacklist")) { startActivity(launchIntent);*/
/* launchIntent = new Intent(getApplicationContext(), BlacklistActivity.class); } else if (itemName.equals("Profile")) {
startActivity(launchIntent);*/ /* launchIntent = new Intent(getApplicationContext(), ProfileActivity.class);
} else if (itemName.equals("Profile")) { startActivity(launchIntent);*/
/* launchIntent = new Intent(getApplicationContext(), ProfileActivity.class); } else if (itemName.equals("Settings")) {
startActivity(launchIntent);*/ launchIntent = new Intent(getApplicationContext(), SettingsActivity.class);
} else if (itemName.equals("Settings")) { startActivity(launchIntent);
launchIntent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(launchIntent);
} else if (itemName.equals("Log out")) { } else if (itemName.equals("Log out")) {
PrefUtils.cleanUserLocalStorage(getApplicationContext()); stopBackgroundLocalizationTask();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName()); PrefUtils.cleanUserLocalStorage(getApplicationContext());
if (i != null) { Intent i = getBaseContext().getPackageManager()
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); .getLaunchIntentForPackage(getBaseContext().getPackageName());
} if (i != null) {
startActivity(i); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
} }
startActivity(i);
finish();
sideDrawer.closeDrawers();
return true;
} }
sideDrawer.closeDrawers();
return true;
} }
); );
navigationView = findViewById(R.id.navigation); navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(this); navigationView.setOnNavigationItemSelectedListener(this);
sharingFragment = new SharingFragment(); sharingFragment = new SharingFragment();
@ -102,6 +105,30 @@ public abstract class BaseActivity
} }
public void stopBackgroundLocalizationTask() {
Intent stopIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
stopIntent.putExtra("request_stop", true);
startService(stopIntent);
}
public void startBackgroundLocalizationTask() {
Intent startIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(startIntent);
} else {
startService(startIntent);
}
}
public void handleBackgroundTaskLifeCycle() {
if (PrefUtils.isEnableSharingLocalization(getApplicationContext())) {
startBackgroundLocalizationTask();
} else {
stopBackgroundLocalizationTask();
}
}
@Override @Override
public void setContentView(int layoutResID) { public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.base_activity, null); DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.base_activity, null);

View File

@ -167,6 +167,7 @@ public class LoginActivity extends AppCompatActivity {
private void loginProcess(String email, String password) { private void loginProcess(String email, String password) {
Log.e("LOGIN", String.valueOf(PrefUtils.getIsTutor(getApplicationContext())));
//Fake validate //Fake validate
LdapUser user = new LdapUser(email, password, "admin", (PrefUtils.getIsTutor(getApplicationContext())) ? "Tutor" : "Student", "string", "string", email); LdapUser user = new LdapUser(email, password, "admin", (PrefUtils.getIsTutor(getApplicationContext())) ? "Tutor" : "Student", "string", "string", email);
@ -202,7 +203,6 @@ public class LoginActivity extends AppCompatActivity {
JWT jwt = new JWT(token); JWT jwt = new JWT(token);
Claim role = jwt.getClaim("nameid"); Claim role = jwt.getClaim("nameid");
PrefUtils.storeIsLoggedIn(getApplicationContext(), true); PrefUtils.storeIsLoggedIn(getApplicationContext(), true);
PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeApiKey(getApplicationContext(), token);
PrefUtils.storeUserId(getApplicationContext(), role.asString()); PrefUtils.storeUserId(getApplicationContext(), role.asString());

View File

@ -6,14 +6,11 @@ import android.animation.ValueAnimator;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import android.os.Handler; import android.os.Handler;
import android.util.Log; import android.util.Log;
import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.annotations.MarkerOptions;
@ -25,7 +22,6 @@ import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.uam.wmi.findmytutor.R; import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.model.Coordinate; import com.uam.wmi.findmytutor.model.Coordinate;
import com.uam.wmi.findmytutor.network.ApiClient; import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.network.RetrofitClientInstance;
import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; import com.uam.wmi.findmytutor.service.BackgroundLocalizationService;
import com.uam.wmi.findmytutor.service.CoordinateService; import com.uam.wmi.findmytutor.service.CoordinateService;
import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.PrefUtils;
@ -91,6 +87,9 @@ public class MapActivity extends BaseActivity
mapView = (MapView) findViewById(R.id.mapView); mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState); mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this); mapView.getMapAsync(this);
//start background task
startBackgroundLocalizationTask();
} }
@Override @Override
@ -237,6 +236,8 @@ public class MapActivity extends BaseActivity
mapView.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState);
} }
/*@Override /*@Override
public void startLocalizationService() { public void startLocalizationService() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {

View File

@ -26,11 +26,8 @@ import java.util.Set;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext; import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
//public class SharingFragment {
//}
public class SharingFragment extends PreferenceFragment { public class SharingFragment extends PreferenceFragment {
Activity mapActivity;
@SuppressLint("ResourceType") @SuppressLint("ResourceType")
@Override @Override
@ -48,41 +45,13 @@ public class SharingFragment extends PreferenceFragment {
locationSharing.setOnPreferenceChangeListener((buttonView, isChecked) -> { locationSharing.setOnPreferenceChangeListener((buttonView, isChecked) -> {
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) isChecked); PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) isChecked);
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle();
if(PrefUtils.isEnableSharingLocalization(getApplicationContext())){
Log.e("BACKGROUND", isChecked.toString());
Intent startIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getActivity().startForegroundService(startIntent);
} else {
getActivity().startService(startIntent);
}
}else{
Log.e("BACKGROUND", "stop");
Intent stopIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
stopIntent.putExtra("request_stop", true);
getActivity().startService(stopIntent);
}
return true; return true;
}); });
} }
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mapActivity = activity;
}
public static SharingFragment newInstance() { public static SharingFragment newInstance() {
return new SharingFragment(); return new SharingFragment();
} }

View File

@ -6,9 +6,11 @@ import android.app.Notification;
import android.app.NotificationChannel; import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.Service; import android.app.Service;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color; import android.graphics.Color;
import android.location.Criteria;
import android.location.Location; import android.location.Location;
import android.location.LocationManager; import android.location.LocationManager;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -17,12 +19,10 @@ import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.os.IBinder; import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.RequiresApi; import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
import android.util.Log; import android.util.Log;
import android.content.Context;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.uam.wmi.findmytutor.model.Coordinate; import com.uam.wmi.findmytutor.model.Coordinate;
@ -30,16 +30,8 @@ import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.PrefUtils;
import com.uam.wmi.findmytutor.utils.RestApiHelper; import com.uam.wmi.findmytutor.utils.RestApiHelper;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.Array;
import java.net.SocketTimeoutException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
@ -50,49 +42,30 @@ import timber.log.Timber;
public class BackgroundLocalizationService extends Service { public class BackgroundLocalizationService extends Service {
public static String str_receiver = "background.location.broadcast";
private static final String TAG = "MyLocationService"; private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 100;
private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 20f;
private static final float LOCATION_DISTANCE = 10f; public static String str_receiver = "background.location.broadcast";
private static long notify_interval = 10000; private static long notify_interval = 10000;
private Handler mHandler = new Handler();
private HandlerThread mHandlerThread = null;
Location mLastLocation; Location mLastLocation;
Intent intent; Intent intent;
private Runnable mStatusChecker;
ArrayList<String> providers = new ArrayList<String>(); ArrayList<String> providers = new ArrayList<String>();
LocationListener[] mLocationListeners ; LocationListener[] mLocationListeners;
private LocationManager mLocationManager = null;
private Handler mHandler = new Handler();
private HandlerThread mHandlerThread = null;
private Runnable mStatusChecker;
private class LocationListener implements android.location.LocationListener { public BackgroundLocalizationService() {
providers.add(LocationManager.GPS_PROVIDER);
providers.add(LocationManager.NETWORK_PROVIDER);
//providers.add(LocationManager.PASSIVE_PROVIDER);
public LocationListener(String provider) { mLocationListeners = new LocationListener[]{
Log.e(TAG, "LocationListener " + provider); new LocationListener(LocationManager.GPS_PROVIDER),
mLastLocation = new Location(provider); new LocationListener(LocationManager.NETWORK_PROVIDER)
} //new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
//fn_update(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 @Override
@ -120,22 +93,11 @@ public class BackgroundLocalizationService extends Service {
return START_STICKY; return START_STICKY;
} }
public BackgroundLocalizationService(){
providers.add(LocationManager.GPS_PROVIDER);
providers.add(LocationManager.NETWORK_PROVIDER);
providers.add(LocationManager.PASSIVE_PROVIDER);
mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
}
@Override @Override
public void onCreate() { public void onCreate() {
Log.e(TAG, "onCreate"); Log.e(TAG, "onCreate");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground(); startMyOwnForeground();
else { else {
@ -156,6 +118,7 @@ public class BackgroundLocalizationService extends Service {
LOCATION_DISTANCE, LOCATION_DISTANCE,
listener listener
); );
} catch (java.lang.SecurityException ex) { } catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex); Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
@ -165,9 +128,8 @@ public class BackgroundLocalizationService extends Service {
providerIndex++; providerIndex++;
} }
mStatusChecker = () -> { mStatusChecker = () -> {
try{ try {
fn_getlocation(); fn_getlocation();
} finally { } finally {
mHandler.postDelayed(mStatusChecker, notify_interval); mHandler.postDelayed(mStatusChecker, notify_interval);
@ -175,7 +137,6 @@ public class BackgroundLocalizationService extends Service {
}; };
AsyncTask.execute(mStatusChecker); AsyncTask.execute(mStatusChecker);
} }
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
@ -199,7 +160,6 @@ public class BackgroundLocalizationService extends Service {
startForeground(2, notification); startForeground(2, notification);
} }
private void fn_getlocation() { private void fn_getlocation() {
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
@ -217,6 +177,7 @@ public class BackgroundLocalizationService extends Service {
for (String provider : providers1) { for (String provider : providers1) {
Location location = mLocationManager.getLastKnownLocation(provider); Location location = mLocationManager.getLastKnownLocation(provider);
Log.e("Location", String.valueOf(location));
if (location == null) { if (location == null) {
continue; continue;
} }
@ -267,6 +228,35 @@ public class BackgroundLocalizationService extends Service {
} }
} }
private class LocationListener implements android.location.LocationListener {
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);
}
@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);
}
}
private class Task extends AsyncTask { private class Task extends AsyncTask {
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;