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.FOREGROUND_SERVICE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"

View File

@ -53,42 +53,45 @@ public abstract class BaseActivity
setContentView(getContentViewId());
drawerNavigationView = findViewById(R.id.nav_view);
sideDrawer = findViewById(R.id.activity_container);
drawerNavigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
String itemName = (String) item.getTitle();
Intent launchIntent;
if (itemName.equals("Whitelist")) {
/* launchIntent = new Intent(getApplicationContext(), WhitelistActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Blacklist")) {
/* launchIntent = new Intent(getApplicationContext(), BlacklistActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Profile")) {
/* launchIntent = new Intent(getApplicationContext(), ProfileActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Settings")) {
launchIntent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(launchIntent);
item -> {
String itemName = (String) item.getTitle();
Intent launchIntent;
if (itemName.equals("Whitelist")) {
/* launchIntent = new Intent(getApplicationContext(), WhitelistActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Blacklist")) {
/* launchIntent = new Intent(getApplicationContext(), BlacklistActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Profile")) {
/* launchIntent = new Intent(getApplicationContext(), ProfileActivity.class);
startActivity(launchIntent);*/
} else if (itemName.equals("Settings")) {
launchIntent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(launchIntent);
} else if (itemName.equals("Log out")) {
PrefUtils.cleanUserLocalStorage(getApplicationContext());
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
if (i != null) {
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(i);
finish();
} else if (itemName.equals("Log out")) {
stopBackgroundLocalizationTask();
PrefUtils.cleanUserLocalStorage(getApplicationContext());
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
if (i != null) {
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(i);
finish();
sideDrawer.closeDrawers();
return true;
}
sideDrawer.closeDrawers();
return true;
}
);
navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(this);
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
public void setContentView(int layoutResID) {
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) {
Log.e("LOGIN", String.valueOf(PrefUtils.getIsTutor(getApplicationContext())));
//Fake validate
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);
Claim role = jwt.getClaim("nameid");
PrefUtils.storeIsLoggedIn(getApplicationContext(), true);
PrefUtils.storeApiKey(getApplicationContext(), token);
PrefUtils.storeUserId(getApplicationContext(), role.asString());

View File

@ -6,14 +6,11 @@ import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
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.util.Log;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
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.model.Coordinate;
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.CoordinateService;
import com.uam.wmi.findmytutor.utils.PrefUtils;
@ -91,6 +87,9 @@ public class MapActivity extends BaseActivity
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
//start background task
startBackgroundLocalizationTask();
}
@Override
@ -237,6 +236,8 @@ public class MapActivity extends BaseActivity
mapView.onSaveInstanceState(outState);
}
/*@Override
public void startLocalizationService() {
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;
//public class SharingFragment {
//}
public class SharingFragment extends PreferenceFragment {
Activity mapActivity;
@SuppressLint("ResourceType")
@Override
@ -48,41 +45,13 @@ public class SharingFragment extends PreferenceFragment {
locationSharing.setOnPreferenceChangeListener((buttonView, isChecked) -> {
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) isChecked);
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);
}
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle();
return true;
});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mapActivity = activity;
}
public static SharingFragment newInstance() {
return new SharingFragment();
}

View File

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