Add stop and start possibility to background task

This commit is contained in:
Mieszko Wrzeszczyński 2018-11-02 21:46:05 +01:00
parent bf694594e4
commit 78957bb62b
7 changed files with 107 additions and 46 deletions

View File

@ -140,12 +140,12 @@ public abstract class BaseActivity
actionBarDrawerToggle.syncState();
if (isTutor) {
fn_permission();
}
/* if (isTutor) {
startLocalizationService();
}*/
}
private void fn_permission() {
/* public void startLocalizationService() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
@ -171,7 +171,7 @@ public abstract class BaseActivity
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
}
}*/
@Override
public void onConfigurationChanged(Configuration newConfig) {

View File

@ -169,7 +169,7 @@ public class LoginActivity extends AppCompatActivity {
private void loginProcess(String email, String password) {
//Fake validate
LdapUser user = new LdapUser(email, password, "admin", (isTutor) ? "Tutor" : "Student", "string", "string", email);
LdapUser user = new LdapUser(email, password, "admin", (PrefUtils.getIsTutor(getApplicationContext())) ? "Tutor" : "Student", "string", "string", email);
// ValidateUser user = new ValidateUser(email, password);

View File

@ -62,8 +62,6 @@ public class MapActivity extends BaseActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -239,7 +237,8 @@ public class MapActivity extends BaseActivity
mapView.onSaveInstanceState(outState);
}
private void fn_permission() {
/*@Override
public void startLocalizationService() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MapActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
@ -265,7 +264,7 @@ public class MapActivity extends BaseActivity
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
}
}*/
@Override
protected int getContentViewId() {

View File

@ -1,8 +1,11 @@
package com.uam.wmi.findmytutor.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
@ -13,41 +16,70 @@ import android.view.View;
import android.view.ViewGroup;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.service.BackgroundLocalizationService;
import com.uam.wmi.findmytutor.utils.PrefUtils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
//public class SharingFragment {
//}
public class SharingFragment extends PreferenceFragment {
Activity mapActivity;
@SuppressLint("ResourceType")
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.pref_sharing);
Preference manualStatus = findPreference("key_manual_status");
Preference locationSharing = findPreference("key_sharing_enabled");
manualStatus.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) findPreference("key_status_value");
updateListPreference(lp, newValue, "manual_statuses");
return true;
});
/* Preference manualLocation = findPreference("key_sharing_enabled");
manualLocation.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) findPreference("key_sharing_enabled");
updateListPreference(lp, newValue, "sharing_enabled");
return true;
});*/
locationSharing.setOnPreferenceChangeListener((buttonView, isChecked) -> {
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) isChecked);
Preference sharingLocation = findPreference("key_sharing_enabled");
sharingLocation.setOnPreferenceChangeListener((preference, o) -> {
Log.e("change", "1");
return false;
});
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;
});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mapActivity = activity;
}
public static SharingFragment newInstance() {
@ -58,7 +90,7 @@ public class SharingFragment extends PreferenceFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
Objects.requireNonNull(view).setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
@ -74,10 +106,10 @@ public class SharingFragment extends PreferenceFragment {
setListPreferenceData(lp.getKey(),manualStatusArr);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(storageKey,manualStatusSet);
editor.commit();
editor.apply();
}
protected ListPreference setListPreferenceData(String lp_name, String [] entries) {
protected void setListPreferenceData(String lp_name, String [] entries) {
ListPreference lp = (ListPreference) findPreference(lp_name);
lp.setEntries(entries);
CharSequence[] entryValues = new CharSequence [entries.length];
@ -88,7 +120,5 @@ public class SharingFragment extends PreferenceFragment {
lp.setDefaultValue("1");
lp.setEntryValues(entryValues);
return lp;
}
}

View File

@ -15,7 +15,9 @@ import android.os.AsyncTask;
import android.os.Build;
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;
@ -55,10 +57,11 @@ public class BackgroundLocalizationService extends Service {
private static final float LOCATION_DISTANCE = 10f;
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 ;
@ -73,7 +76,7 @@ public class BackgroundLocalizationService extends Service {
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
fn_update(mLastLocation);
//fn_update(mLastLocation);
}
@Override
@ -102,6 +105,18 @@ public class BackgroundLocalizationService extends Service {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
//call startForeground first
boolean stopService = false;
if (intent != null) {
stopService = intent.getBooleanExtra("request_stop", false);
}
if (stopService) {
stopForeground(true);
stopSelf();
return START_STICKY;
}
return START_STICKY;
}
@ -150,11 +165,17 @@ public class BackgroundLocalizationService extends Service {
providerIndex++;
}
Timer mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
mStatusChecker = () -> {
try{
fn_getlocation();
} finally {
mHandler.postDelayed(mStatusChecker, notify_interval);
}
};
AsyncTask.execute(mStatusChecker);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@ -210,13 +231,6 @@ public class BackgroundLocalizationService extends Service {
fn_update(bestLocation);
}
private class TimerTaskToGetLocation extends TimerTask {
@Override
public void run() {
mHandler.post(BackgroundLocalizationService.this::fn_getlocation);
}
}
private void fn_update(Location location) {
new Task(location).execute();
}
@ -226,6 +240,9 @@ public class BackgroundLocalizationService extends Service {
Log.e(TAG, "onDestroy");
super.onDestroy();
mHandler.removeCallbacks(mStatusChecker);
if (mLocationManager != null) {
for (LocationListener listener : mLocationListeners) {
try {
@ -233,6 +250,8 @@ public class BackgroundLocalizationService extends Service {
return;
}
mLocationManager.removeUpdates(listener);
Log.i(TAG, "Removed");
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}

View File

@ -7,15 +7,26 @@ import android.util.Log;
import com.auth0.android.jwt.Claim;
import com.auth0.android.jwt.JWT;
import java.util.Map;
public class PrefUtils {
public PrefUtils() {
}
private static SharedPreferences getSharedPreferences(Context context) {
public static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE);
}
public static void getAllKeys(Context context){
Map<String,?> keys = getSharedPreferences(context).getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
public static void cleanUserLocalStorage(Context context) {
SharedPreferences preferences = getSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
@ -67,14 +78,14 @@ public class PrefUtils {
return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false);
}
public static void storeIsServiceRunning(Context context, Boolean flag) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putBoolean("IS_SERVIS_RUNNING", flag);
editor.apply();
public static boolean isEnableSharingLocalization(Context context) {
return getSharedPreferences(context).getBoolean("IS_ENABLE_SHARING_LOCALIZATION", false);
}
public static boolean getIsServiceRunning(Context context) {
return getSharedPreferences(context).getBoolean("IS_SERVIS_RUNNING", false);
public static void storeEnableSharingLocalization(Context context,Boolean isChecked) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putBoolean("IS_ENABLE_SHARING_LOCALIZATION", isChecked);
editor.apply();
}
public static void storeUserFirstName(Context context, String userName) {

View File

@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<PreferenceCategory android:title="@string/settings_category_general">