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(); actionBarDrawerToggle.syncState();
if (isTutor) { /* if (isTutor) {
fn_permission(); startLocalizationService();
} }*/
} }
private void fn_permission() { /* 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)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) { 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(); Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
} }
} }
} }*/
@Override @Override
public void onConfigurationChanged(Configuration newConfig) { public void onConfigurationChanged(Configuration newConfig) {

View File

@ -169,7 +169,7 @@ public class LoginActivity extends AppCompatActivity {
private void loginProcess(String email, String password) { private void loginProcess(String email, String password) {
//Fake validate //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); // ValidateUser user = new ValidateUser(email, password);

View File

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

View File

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

View File

@ -15,7 +15,9 @@ import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
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;
@ -55,10 +57,11 @@ public class BackgroundLocalizationService extends Service {
private static final float LOCATION_DISTANCE = 10f; private static final float LOCATION_DISTANCE = 10f;
private static long notify_interval = 10000; private static long notify_interval = 10000;
private Handler mHandler = new Handler(); 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 ;
@ -73,7 +76,7 @@ public class BackgroundLocalizationService extends Service {
public void onLocationChanged(Location location) { public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location); Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location); mLastLocation.set(location);
fn_update(mLastLocation); //fn_update(mLastLocation);
} }
@Override @Override
@ -102,6 +105,18 @@ public class BackgroundLocalizationService extends Service {
Log.e(TAG, "onStartCommand"); Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId); 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; return START_STICKY;
} }
@ -150,11 +165,17 @@ public class BackgroundLocalizationService extends Service {
providerIndex++; providerIndex++;
} }
Timer mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
fn_getlocation(); mStatusChecker = () -> {
try{
fn_getlocation();
} finally {
mHandler.postDelayed(mStatusChecker, notify_interval);
}
};
AsyncTask.execute(mStatusChecker);
} }
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
@ -210,13 +231,6 @@ public class BackgroundLocalizationService extends Service {
fn_update(bestLocation); fn_update(bestLocation);
} }
private class TimerTaskToGetLocation extends TimerTask {
@Override
public void run() {
mHandler.post(BackgroundLocalizationService.this::fn_getlocation);
}
}
private void fn_update(Location location) { private void fn_update(Location location) {
new Task(location).execute(); new Task(location).execute();
} }
@ -226,6 +240,9 @@ public class BackgroundLocalizationService extends Service {
Log.e(TAG, "onDestroy"); Log.e(TAG, "onDestroy");
super.onDestroy(); super.onDestroy();
mHandler.removeCallbacks(mStatusChecker);
if (mLocationManager != null) { if (mLocationManager != null) {
for (LocationListener listener : mLocationListeners) { for (LocationListener listener : mLocationListeners) {
try { try {
@ -233,6 +250,8 @@ public class BackgroundLocalizationService extends Service {
return; return;
} }
mLocationManager.removeUpdates(listener); mLocationManager.removeUpdates(listener);
Log.i(TAG, "Removed");
} catch (Exception ex) { } catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", 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.Claim;
import com.auth0.android.jwt.JWT; import com.auth0.android.jwt.JWT;
import java.util.Map;
public class PrefUtils { public class PrefUtils {
public PrefUtils() { public PrefUtils() {
} }
private static SharedPreferences getSharedPreferences(Context context) { public static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE); 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) { public static void cleanUserLocalStorage(Context context) {
SharedPreferences preferences = getSharedPreferences(context); SharedPreferences preferences = getSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
@ -67,14 +78,14 @@ public class PrefUtils {
return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false); return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false);
} }
public static void storeIsServiceRunning(Context context, Boolean flag) { public static boolean isEnableSharingLocalization(Context context) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit(); return getSharedPreferences(context).getBoolean("IS_ENABLE_SHARING_LOCALIZATION", false);
editor.putBoolean("IS_SERVIS_RUNNING", flag);
editor.apply();
} }
public static boolean getIsServiceRunning(Context context) { public static void storeEnableSharingLocalization(Context context,Boolean isChecked) {
return getSharedPreferences(context).getBoolean("IS_SERVIS_RUNNING", false); SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putBoolean("IS_ENABLE_SHARING_LOCALIZATION", isChecked);
editor.apply();
} }
public static void storeUserFirstName(Context context, String userName) { public static void storeUserFirstName(Context context, String userName) {

View File

@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?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"> <PreferenceCategory android:title="@string/settings_category_general">