diff --git a/opentripplanner-android/src/main/AndroidManifest.xml b/opentripplanner-android/src/main/AndroidManifest.xml index abd5ff81..0b4f9fc8 100644 --- a/opentripplanner-android/src/main/AndroidManifest.xml +++ b/opentripplanner-android/src/main/AndroidManifest.xml @@ -69,6 +69,10 @@ android:theme="@style/MyTheme" android:windowSoftInputMode="stateHidden"> + + + + diff --git a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/fragments/MainFragment.java b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/fragments/MainFragment.java index 4f2e55c1..ae468b7c 100644 --- a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/fragments/MainFragment.java +++ b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/fragments/MainFragment.java @@ -53,6 +53,7 @@ import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; +import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.text.Editable; @@ -162,10 +163,13 @@ import edu.usf.cutr.opentripplanner.android.sqlite.ServersDataSource; import edu.usf.cutr.opentripplanner.android.tasks.BikeRentalLoad; import edu.usf.cutr.opentripplanner.android.tasks.MetadataRequest; +import edu.usf.cutr.opentripplanner.android.tasks.MetadataRequest.MetadataRequestReceiver; import edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding; +import edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding.OTPGeocodingReceiver; import edu.usf.cutr.opentripplanner.android.tasks.RequestTimesForTrips; import edu.usf.cutr.opentripplanner.android.tasks.ServerChecker; import edu.usf.cutr.opentripplanner.android.tasks.ServerSelector; +import edu.usf.cutr.opentripplanner.android.tasks.ServerSelector.ServerSelectorReceiver; import edu.usf.cutr.opentripplanner.android.tasks.TripRequest; import edu.usf.cutr.opentripplanner.android.util.BikeRentalStationInfo; import edu.usf.cutr.opentripplanner.android.util.ConversionUtils; @@ -195,6 +199,11 @@ public class MainFragment extends Fragment implements GooglePlayServicesClient.ConnectionCallbacks, GoogleMap.OnCameraChangeListener { + public static final String SERVERSELECTOR_FILTER = "MainFragment_mServerSelectorReceiver"; + public static final String SERVERSELECTOR_NOLOCATION_FILTER = "MainFragment_mServerSelectorReceiverNoLocation"; + public static final String METADATA_FILTER = "MainFragment_metadatRequestReceiver"; + public static final String OTPGEOCODING_FILTER = "MainFragment_otpGeocodingReceiver"; + private static LocationManager sLocationManager; private OTPApp mOTPApp; @@ -358,7 +367,13 @@ public class MainFragment extends Fragment implements private GraphMetadata mCustomServerMetadata = null; - private OTPGeocoding mGeoCodingTask; + private MetadataRequestReceiver mMetadatRequestReceiver; + + private OTPGeocodingReceiver mOtpGeocodingReceiver; + + private ServerSelectorReceiver mServerSelectorReceiver; + + private ServerSelectorReceiver mServerSelectorReceiverNoLocation; @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @@ -396,6 +411,26 @@ public void onAttach(Activity activity) { throw new ClassCastException(activity.toString() + " must implement OtpFragment"); } + mMetadatRequestReceiver = new MetadataRequestReceiver(activity, activity.getApplicationContext(), this); + LocalBroadcastManager.getInstance(activity) + .registerReceiver(mMetadatRequestReceiver, new IntentFilter(METADATA_FILTER)); + } + + @Override + public void onDetach() { + super.onDetach(); + if (mMetadatRequestReceiver != null) { + LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMetadatRequestReceiver); + } + if (mOtpGeocodingReceiver != null) { + LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mOtpGeocodingReceiver); + } + if (mServerSelectorReceiver != null) { + LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mServerSelectorReceiver); + } + if (mServerSelectorReceiverNoLocation != null) { + LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mServerSelectorReceiverNoLocation); + } } @Override @@ -2087,11 +2122,16 @@ public void runAutoDetectServer(LatLng mCurrentLatLng, boolean showDialog) { Toast.LENGTH_LONG).show(); } else { ServersDataSource dataSource = ServersDataSource.getInstance(mApplicationContext); - WeakReference weakContext = new WeakReference(getActivity()); - - ServerSelector serverSelector = new ServerSelector(weakContext, mApplicationContext, - dataSource, this, mNeedToUpdateServersList, showDialog); - serverSelector.execute(mCurrentLatLng); + mServerSelectorReceiver = new ServerSelectorReceiver(getActivity(), mApplicationContext, + dataSource, this, showDialog); + LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mServerSelectorReceiver, + new IntentFilter(SERVERSELECTOR_FILTER)); + Intent serverSelector = new Intent(getActivity(), ServerSelector.class); + mServerSelectorReceiver.showProgressDialog(); + serverSelector.putExtra("latLng", mCurrentLatLng); + serverSelector.putExtra("mustRefreshList", mNeedToUpdateServersList); + serverSelector.putExtra("FILTER", SERVERSELECTOR_FILTER); + getActivity().startService(serverSelector); mSavedLastLocationCheckedForServer = mCurrentLatLng; } setNeedToRunAutoDetect(false); @@ -2108,13 +2148,16 @@ public void runAutoDetectServer(LatLng mCurrentLatLng, boolean showDialog) { */ public void runAutoDetectServerNoLocation(boolean showDialog) { ServersDataSource dataSource = ServersDataSource.getInstance(mApplicationContext); - WeakReference weakContext = new WeakReference(getActivity()); + mServerSelectorReceiverNoLocation = new ServerSelectorReceiver(getActivity(), mApplicationContext, + dataSource, this, showDialog); + LocalBroadcastManager.getInstance(getActivity()) + .registerReceiver(mServerSelectorReceiverNoLocation, new IntentFilter(SERVERSELECTOR_NOLOCATION_FILTER)); + Intent serverSelector = new Intent(getActivity(), ServerSelector.class); + mServerSelectorReceiverNoLocation.showProgressDialog(); + serverSelector.putExtra("mustRefreshList", mNeedToUpdateServersList); + serverSelector.putExtra("FILTER", SERVERSELECTOR_NOLOCATION_FILTER); + getActivity().startService(serverSelector); - ServerSelector serverSelector = new ServerSelector(weakContext, mApplicationContext, - dataSource, this, mNeedToUpdateServersList, showDialog); - LatLng latLngList[] = new LatLng[1]; - latLngList[0] = null; - serverSelector.execute(latLngList); setNeedToRunAutoDetect(false); setNeedToUpdateServersList(false); } @@ -2548,24 +2591,28 @@ public void processAddress(final boolean isStartTextBox, String address, */ public void processAddress(final boolean isStartTextBox, String address, Double originalLat, Double originalLon, boolean geocodingForMarker) { - WeakReference weakContext = new WeakReference(getActivity()); - mGeoCodingTask = new OTPGeocoding(weakContext, mApplicationContext, - isStartTextBox, geocodingForMarker, mOTPApp.getSelectedServer(), this); + mOtpGeocodingReceiver = new OTPGeocodingReceiver(isStartTextBox, geocodingForMarker, this); + LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mOtpGeocodingReceiver, + new IntentFilter(OTPGEOCODING_FILTER)); LatLng mCurrentLatLng = getLastLocation(); if (address.equalsIgnoreCase(this.getResources().getString(R.string.text_box_my_location))) { if (mCurrentLatLng != null) { if (isStartTextBox){ mIsStartLocationGeocodingCompleted = false; - mGeoCodingTask.execute(address, String.valueOf(mCurrentLatLng.latitude), - String.valueOf(mCurrentLatLng.longitude)); } else{ mIsEndLocationGeocodingCompleted = false; - mGeoCodingTask.execute(address, String.valueOf(mCurrentLatLng.latitude), - String.valueOf(mCurrentLatLng.longitude)); } + Intent optGeocoding = new Intent(getActivity(), OTPGeocoding.class); + String[] params = { address, String.valueOf(mCurrentLatLng.latitude), + String.valueOf(mCurrentLatLng.longitude) }; + optGeocoding.putExtra("params", params); + optGeocoding.putExtra("selectedServer", mOTPApp.getSelectedServer()); + optGeocoding.putExtra("geocodingForMarker", geocodingForMarker); + optGeocoding.putExtra("FILTER", OTPGEOCODING_FILTER); + getActivity().startService(optGeocoding); } else { Toast.makeText(mApplicationContext, mApplicationContext.getResources() @@ -2584,12 +2631,17 @@ public void processAddress(final boolean isStartTextBox, String address, Double } if (isStartTextBox){ mIsStartLocationGeocodingCompleted = false; - mGeoCodingTask.execute(address, latString, lonString); } else{ mIsEndLocationGeocodingCompleted = false; - mGeoCodingTask.execute(address, latString, lonString); } + Intent optGeocoding = new Intent(getActivity(), OTPGeocoding.class); + String[] params = { address, latString, lonString }; + optGeocoding.putExtra("params", params); + optGeocoding.putExtra("selectedServer", mOTPApp.getSelectedServer()); + optGeocoding.putExtra("geocodingForMarker", geocodingForMarker); + optGeocoding.putExtra("FILTER", OTPGEOCODING_FILTER); + getActivity().startService(optGeocoding); } } @@ -2651,9 +2703,11 @@ public void updateSelectedServer(boolean updateUI) { WeakReference weakContext = new WeakReference(getActivity()); if (mCustomServerMetadata == null){ - MetadataRequest metaRequest = new MetadataRequest(weakContext, mApplicationContext, - this); - metaRequest.execute(mPrefs.getString(OTPApp.PREFERENCE_KEY_CUSTOM_SERVER_URL, "")); + Intent metaRequest = new Intent(getActivity(), MetadataRequest.class); + mMetadatRequestReceiver.showProgressDialog(); + metaRequest.putExtra("reqs", mPrefs.getString(OTPApp.PREFERENCE_KEY_CUSTOM_SERVER_URL, "")); + metaRequest.putExtra("FILTER", METADATA_FILTER); + getActivity().startService(metaRequest); } else{ onMetadataRequestComplete(mCustomServerMetadata, false); diff --git a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/model/Server.java b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/model/Server.java index b4729533..a29d99bc 100644 --- a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/model/Server.java +++ b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/model/Server.java @@ -26,7 +26,9 @@ * Modified by Khoa Tran */ -public class Server { +public class Server implements java.io.Serializable { + + private static final long serialVersionUID = 7306023856160948263L; private long id; diff --git a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/MetadataRequest.java b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/MetadataRequest.java index 88b221a1..f3f47ac4 100644 --- a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/MetadataRequest.java +++ b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/MetadataRequest.java @@ -22,10 +22,14 @@ import org.opentripplanner.api.ws.GraphMetadata; import android.app.Activity; +import android.app.IntentService; import android.app.ProgressDialog; +import android.content.BroadcastReceiver; import android.content.Context; +import android.content.Intent; import android.os.AsyncTask; import android.preference.PreferenceManager; +import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; @@ -41,52 +45,22 @@ /** * @author Khoa Tran */ +public class MetadataRequest extends IntentService { + ObjectMapper mapper; -public class MetadataRequest extends AsyncTask { - - private ProgressDialog progressDialog; - - private WeakReference activity; - - private Context context; - - private MetadataRequestCompleteListener callback; - - private static ObjectMapper mapper = null; - - public MetadataRequest(WeakReference activity, Context context, - MetadataRequestCompleteListener callback) { - this.activity = activity; - this.context = context; - this.callback = callback; - Activity activityRetrieved = activity.get(); - if (activityRetrieved != null) { - progressDialog = new ProgressDialog(activityRetrieved); - } + public MetadataRequest() { + super("MetadataRequest"); } - protected void onPreExecute() { - if (activity.get() != null) { - progressDialog.setIndeterminate(true); - progressDialog.setCancelable(true); - Activity activityRetrieved = activity.get(); - if (activityRetrieved != null) { - progressDialog = ProgressDialog.show(activityRetrieved, "", - context.getResources().getString(R.string.task_progress_metadata_progress), true); - } - } - } - - protected GraphMetadata doInBackground(String... reqs) { - String prefix = PreferenceManager.getDefaultSharedPreferences(context) - .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX - , OTPApp.FOLDER_STRUCTURE_PREFIX_NEW); - String u = reqs[0] + prefix + OTPApp.METADATA_LOCATION; + public void onHandleIntent(Intent intent) { + String reqs = intent.getStringExtra("reqs"); + String prefix = PreferenceManager.getDefaultSharedPreferences(this) + .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX, + OTPApp.FOLDER_STRUCTURE_PREFIX_NEW); + String u = reqs + prefix + OTPApp.METADATA_LOCATION; Log.d(OTPApp.TAG, "URL: " + u); - HttpURLConnection urlConnection = null; GraphMetadata metadata = null; - try { URL url = new URL(u); if (mapper == null) { @@ -106,11 +80,38 @@ protected GraphMetadata doInBackground(String... reqs) { urlConnection.disconnect(); } } - return metadata; + Intent resultIntent = new Intent(intent.getStringExtra("FILTER")); + resultIntent.putExtra("metadata", metadata); + LocalBroadcastManager.getInstance(this).sendBroadcast(resultIntent); } - protected void onPostExecute(GraphMetadata metadata) { - if (activity.get() != null) { + public static class MetadataRequestReceiver extends BroadcastReceiver { + + private ProgressDialog progressDialog; + + private Activity activity; + + private Context context; + + private MetadataRequestCompleteListener callback; + + public MetadataRequestReceiver(Activity activity, Context context, + MetadataRequestCompleteListener callback) { + this.activity = activity; + this.context = context; + this.callback = callback; + progressDialog = new ProgressDialog(activity); + } + + public void showProgressDialog() { + progressDialog.setIndeterminate(true); + progressDialog.setCancelable(true); + progressDialog = ProgressDialog.show(activity, "", + context.getResources().getString(R.string.task_progress_metadata_progress), true); + } + + public void onReceive(Context receiverContext, Intent receiverIntent) { + GraphMetadata metadata = (GraphMetadata) receiverIntent.getSerializableExtra("metadata"); try { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); @@ -118,18 +119,19 @@ protected void onPostExecute(GraphMetadata metadata) { } catch (Exception e) { Log.e(OTPApp.TAG, "Error in Metadata Request PostExecute dismissing dialog: " + e); } - } - if (metadata != null) { - Toast.makeText(context, - context.getResources().getString(R.string.toast_metadata_request_successful), - Toast.LENGTH_SHORT).show(); - callback.onMetadataRequestComplete(metadata, true); - } else { - Toast.makeText(context, context.getResources().getString(R.string.toast_server_checker_info_error), - Toast.LENGTH_SHORT).show(); + if (metadata != null) { + Toast.makeText(context, + context.getResources().getString(R.string.toast_metadata_request_successful), + Toast.LENGTH_SHORT).show(); + callback.onMetadataRequestComplete(metadata, true); + } else { + Toast.makeText(context, context.getResources().getString(R.string.toast_server_checker_info_error), + Toast.LENGTH_SHORT).show(); - Log.e(OTPApp.TAG, "No metadata!"); + Log.e(OTPApp.TAG, "No metadata!"); + } } } } + diff --git a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/OTPGeocoding.java b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/OTPGeocoding.java index 689eccca..79a6e074 100644 --- a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/OTPGeocoding.java +++ b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/OTPGeocoding.java @@ -18,12 +18,14 @@ import android.app.Activity; import android.app.AlertDialog; +import android.app.IntentService; +import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; -import android.os.AsyncTask; +import android.content.Intent; +import android.support.v4.content.LocalBroadcastManager; import android.util.Log; -import java.lang.ref.WeakReference; import java.util.ArrayList; import edu.usf.cutr.opentripplanner.android.OTPApp; @@ -37,64 +39,48 @@ * @author Khoa Tran */ -public class OTPGeocoding extends AsyncTask { +public class OTPGeocoding extends IntentService { + Server selectedServer; + boolean geocodingForMarker; + ArrayList addressesReturn; - private WeakReference activity; - - private Context context; - - private boolean isStartTextbox; + public OTPGeocoding() { + super("OTPGeocoding"); + } - private OTPGeocodingListener callback; + public void onHandleIntent(Intent intent) { + this.selectedServer = (Server) intent.getSerializableExtra("selectedServer"); + this.geocodingForMarker = intent.getBooleanExtra("geocodingForMarker", false); + String[] reqs = intent.getStringArrayExtra("params"); + long count = reqs.length; + addressesReturn = LocationUtil.processGeocoding(this, selectedServer, geocodingForMarker, reqs); + Intent resultIntent = new Intent(intent.getStringExtra("FILTER")); + resultIntent.putExtra("count", count); + resultIntent.putExtra("addressesReturn", addressesReturn); + LocalBroadcastManager.getInstance(this).sendBroadcast(resultIntent); + } - private boolean geocodingForMarker; + public static class OTPGeocodingReceiver extends BroadcastReceiver { - private ArrayList addressesReturn = new ArrayList(); + private boolean isStartTextbox; - private Server selectedServer; + private OTPGeocodingListener callback; - public OTPGeocoding(WeakReference activity, Context context, boolean isStartTextbox, - boolean geocodingForMarker, Server selectedServer, - OTPGeocodingListener callback) { - this.context = context; - this.activity = activity; - this.isStartTextbox = isStartTextbox; - this.callback = callback; - this.selectedServer = selectedServer; - this.geocodingForMarker = geocodingForMarker; - } + private boolean geocodingForMarker; - protected void onPreExecute() { - // Do nothing - } + private ArrayList addressesReturn; - protected Long doInBackground(String... reqs) { - long count = reqs.length; - addressesReturn = LocationUtil.processGeocoding(context, selectedServer, geocodingForMarker, reqs); - return count; - } - - protected void onCancelled(Long result) { - Activity activityRetrieved = activity.get(); - if (activityRetrieved != null) { - AlertDialog.Builder geocoderAlert = new AlertDialog.Builder(activityRetrieved); - geocoderAlert.setTitle(R.string.geocoder_results_title) - .setMessage(R.string.geocoder_results_no_results_message) - .setCancelable(false) - .setPositiveButton(context.getResources().getString(android.R.string.ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - } - } - ); - - AlertDialog alert = geocoderAlert.create(); - alert.show(); + public OTPGeocodingReceiver(boolean isStartTextbox, boolean geocodingForMarker, + OTPGeocodingListener callback) { + this.isStartTextbox = isStartTextbox; + this.callback = callback; + this.geocodingForMarker = geocodingForMarker; } - Log.e(OTPApp.TAG, "No geocoding processed!"); - } - protected void onPostExecute(Long result) { - callback.onOTPGeocodingComplete(isStartTextbox, addressesReturn, geocodingForMarker); + public void onReceive(Context receiverContext, Intent receiverIntent) { + Long result = (Long) receiverIntent.getSerializableExtra("count"); + addressesReturn = (ArrayList) receiverIntent.getSerializableExtra("addressesReturn"); + callback.onOTPGeocodingComplete(isStartTextbox, addressesReturn, geocodingForMarker); + } } -} \ No newline at end of file +} diff --git a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/ServerSelector.java b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/ServerSelector.java index 65204301..eddc63d9 100644 --- a/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/ServerSelector.java +++ b/opentripplanner-android/src/main/java/edu/usf/cutr/opentripplanner/android/tasks/ServerSelector.java @@ -18,12 +18,15 @@ import android.app.Activity; import android.app.AlertDialog; +import android.app.IntentService; import android.app.ProgressDialog; +import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; +import android.content.Intent; import android.content.SharedPreferences; -import android.os.AsyncTask; import android.preference.PreferenceManager; +import android.support.v4.content.LocalBroadcastManager; import android.text.Editable; import android.util.Log; import android.webkit.URLUtil; @@ -68,72 +71,28 @@ * @author Khoa Tran */ -public class ServerSelector extends AsyncTask - implements ServerCheckerCompleteListener { - +public class ServerSelector extends IntentService { private Server selectedServer; - - private ProgressDialog progressDialog; - - private WeakReference activity; - - private Context context; - + private boolean mustRefreshList; + private boolean isAutoDetectEnabled; private static List knownServers = new ArrayList(); + private ServersDataSource dataSource; - private boolean mustRefreshList = false; - - private boolean isAutoDetectEnabled = true; - - private ServerSelectorCompleteListener callback; - - private boolean selectedCustomServer; - - private boolean showDialog; - - public ServersDataSource dataSource = null; - - /** - * Constructs a new ServerSelector - * - * @param mustRefreshList true if we should download a new list of servers from the Google - * Doc, false if we should use cached list of servers - * @param showDialog true if a progress dialog is requested - */ - public ServerSelector(WeakReference activity, Context context, - ServersDataSource dataSource, ServerSelectorCompleteListener callback, - boolean mustRefreshList, boolean showDialog) { - this.activity = activity; - this.context = context; - this.dataSource = dataSource; - this.callback = callback; - this.mustRefreshList = mustRefreshList; - this.showDialog = showDialog; - Activity activityRetrieved = activity.get(); - if ((activityRetrieved != null) && showDialog) { - progressDialog = new ProgressDialog(activityRetrieved); - } + public ServerSelector() { + super("ServerSelector"); } - protected void onPreExecute() { - Activity activityRetrieved = activity.get(); - if ((activityRetrieved != null) && showDialog) { - progressDialog.setIndeterminate(true); - progressDialog.setCancelable(true); - progressDialog = ProgressDialog.show(activityRetrieved, "", - context.getResources().getString(R.string.task_progress_server_selector_progress), true); - } - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - - isAutoDetectEnabled = prefs.getBoolean(OTPApp.PREFERENCE_KEY_AUTO_DETECT_SERVER, - true); + private void init(Intent intent) { + this.mustRefreshList = intent.getBooleanExtra("mustRefreshList", false); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + isAutoDetectEnabled = prefs.getBoolean(OTPApp.PREFERENCE_KEY_AUTO_DETECT_SERVER, true); } - - protected Integer doInBackground(LatLng... latLng) { - LatLng currentLocation = latLng[0]; - + public void onHandleIntent(Intent intent) { + init(intent); + LatLng latLng = (LatLng) intent.getParcelableExtra("latLng"); + dataSource = ServersDataSource.getInstance(getApplicationContext()); + LatLng currentLocation = latLng; List serverList = null; // If not forced to refresh list @@ -149,7 +108,7 @@ protected Integer doInBackground(LatLng... latLng) { Log.d(OTPApp.TAG, "No data from sqlite. Attempt retrieving servers from google spreadsheet"); serverList = downloadServerList( - context.getResources().getString(R.string.servers_spreadsheet_url)); + getResources().getString(R.string.servers_spreadsheet_url)); // Insert new list to database if (serverList != null && !serverList.isEmpty()) { @@ -159,10 +118,12 @@ protected Integer doInBackground(LatLng... latLng) { // If still null if (serverList == null || serverList.isEmpty()) { - return null; + Intent resultIntent = new Intent(intent.getStringExtra("FILTER")); + resultIntent.putExtra("selectedServer", selectedServer); + LocalBroadcastManager.getInstance(this).sendBroadcast(resultIntent); + return; } } - knownServers.clear(); knownServers.addAll(serverList); @@ -171,7 +132,21 @@ protected Integer doInBackground(LatLng... latLng) { selectedServer = findOptimalSever(currentLocation); } - return serverList.size(); + Intent resultIntent = new Intent( + intent.getStringExtra("return_action")); + resultIntent.putExtra("serverListSize", serverList.size()); + resultIntent.putExtra("selectedServer", selectedServer); + LocalBroadcastManager.getInstance(this).sendBroadcast(resultIntent); + } + + private void insertServerListToDatabase(List servers) { + dataSource.open(); + for (Server server : servers) { + if (dataSource.createServer(server) == null) { + Log.e(OTPApp.TAG, "Some server fields are incorrect, server not added"); + } + } + dataSource.close(); } private List getServersFromSQLite() { @@ -196,7 +171,7 @@ private List getServersFromSQLite() { servers = null; } dataSource.close(); -// Toast.makeText(activity.getApplicationContext(), shown, Toast.LENGTH_SHORT).show(); +// Toast.makeText(activity.getApplicationContext(), shown, Toast.LENGTH_SHORT).show(); return servers; } @@ -288,16 +263,6 @@ private List downloadServerList(String urlString) { } - private void insertServerListToDatabase(List servers) { - dataSource.open(); - for (Server server : servers) { - if (dataSource.createServer(server) == null) { - Log.e(OTPApp.TAG, "Some server fields are incorrect, server not added"); - } - } - dataSource.close(); - } - /** * Automatically detects the correct OTP server based on the location of the device * @@ -330,42 +295,86 @@ private Server findOptimalSever(LatLng currentLocation) { return server; } - protected void onPostExecute(Integer result) { - if ((activity.get() != null) && showDialog) { - try { - if (progressDialog != null && progressDialog.isShowing()) { - progressDialog.dismiss(); - } - } catch (Exception e) { - Log.e(OTPApp.TAG, "Error in Server Selector PostExecute dismissing dialog: " + e); + public static class ServerSelectorReceiver extends BroadcastReceiver + implements ServerCheckerCompleteListener { + private Server selectedServer; + + private ProgressDialog progressDialog; + + private Activity activity; + + private Context context; + + private ServerSelectorCompleteListener callback; + + private boolean selectedCustomServer; + + private boolean showDialog; + + public ServersDataSource dataSource = null; + + /** + * Constructs a new ServerSelector + * + * @param mustRefreshList true if we should download a new list of servers from the Google + * Doc, false if we should use cached list of servers + * @param showDialog true if a progress dialog is requested + */ + public ServerSelectorReceiver(Activity activity, Context context, + ServersDataSource dataSource, ServerSelectorCompleteListener callback, boolean showDialog) { + this.activity = activity; + this.context = context; + this.dataSource = dataSource; + this.callback = callback; + this.showDialog = showDialog; + this.progressDialog = new ProgressDialog(activity); + } + + public void showProgressDialog() { + if (showDialog) { + progressDialog.setIndeterminate(true); + progressDialog.setCancelable(true); + progressDialog = ProgressDialog.show(activity, "", + context.getResources().getString(R.string.task_progress_server_selector_progress), true); } } - if (selectedServer != null) { - //We've already auto-selected a server - ServerChecker serverChecker = new ServerChecker(activity, - context, ServerSelector.this, false, false, true); - serverChecker.execute(selectedServer); - } else if (knownServers != null && !knownServers.isEmpty()) { - Log.d(OTPApp.TAG, - "No server automatically selected. User will need to choose the OTP server."); - // Create dialog for user to choose - List serverNames = new ArrayList(); - for (Server server : knownServers) { - serverNames.add(server.getRegion()); + public void onReceive(Context receiverContext, Intent receiverIntent) { + Integer result = (Integer) receiverIntent.getSerializableExtra("serverListSize"); + selectedServer = (Server) receiverIntent.getSerializableExtra("selectedServer"); + if (showDialog) { + try { + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.dismiss(); + } + } catch (Exception e) { + Log.e(OTPApp.TAG, "Error in Server Selector PostExecute dismissing dialog: " + e); + } } - Collections.sort(serverNames); + if (selectedServer != null) { + //We've already auto-selected a server + ServerChecker serverChecker = new ServerChecker(new WeakReference(activity), + context, ServerSelectorReceiver.this, false, false, true); + serverChecker.execute(selectedServer); + } else if (knownServers != null && !knownServers.isEmpty()) { + Log.d(OTPApp.TAG, + "No server automatically selected. User will need to choose the OTP server."); + + // Create dialog for user to choose + List serverNames = new ArrayList(); + for (Server server : knownServers) { + serverNames.add(server.getRegion()); + } - serverNames.add(0, context.getResources().getString(R.string.server_checker_info_custom_server_name)); + Collections.sort(serverNames); - final CharSequence[] items = serverNames.toArray(new CharSequence[serverNames.size()]); + serverNames.add(0, context.getResources().getString(R.string.server_checker_info_custom_server_name)); - Activity activityRetrieved = activity.get(); + final CharSequence[] items = serverNames.toArray(new CharSequence[serverNames.size()]); - if (activityRetrieved != null) { - AlertDialog.Builder builder = new AlertDialog.Builder(activityRetrieved); + AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(context.getResources() .getString(R.string.server_checker_info_title)); builder.setItems(items, new DialogInterface.OnClickListener() { @@ -378,68 +387,63 @@ public void onClick(DialogInterface dialog, int item) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); - Activity activityRetrieved = activity.get(); - - if (activityRetrieved != null) { - final EditText tbBaseURL = new EditText(activityRetrieved); - String actualCustomServer = prefs - .getString(PREFERENCE_KEY_CUSTOM_SERVER_URL, ""); - tbBaseURL.setText(actualCustomServer); - - AlertDialog.Builder urlAlert = new AlertDialog.Builder( - activityRetrieved); - urlAlert.setTitle(context.getResources() - .getString( - R.string.server_selector_custom_server_alert_title)); - urlAlert.setView(tbBaseURL); - urlAlert.setPositiveButton( - context.getResources().getString(android.R.string.ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - Editable tbEditable = tbBaseURL.getText(); - if (tbEditable != null) { - String value = tbEditable.toString().trim(); - if (URLUtil.isValidUrl(value)) { - SharedPreferences.Editor prefsEditor - = PreferenceManager - .getDefaultSharedPreferences( - context) - .edit(); - prefsEditor - .putString( - PREFERENCE_KEY_CUSTOM_SERVER_URL, - value); - - ServerChecker serverChecker - = new ServerChecker(activity, - context, ServerSelector.this, true, - true, false); - serverChecker.execute( - new Server(value, context)); - prefsEditor.commit(); - } else { - Toast.makeText(context, - context.getResources() - .getString( - R.string.settings_menu_custom_server_url_description_error_url), - Toast.LENGTH_SHORT).show(); - } + final EditText tbBaseURL = new EditText(activity); + String actualCustomServer = prefs + .getString(PREFERENCE_KEY_CUSTOM_SERVER_URL, ""); + tbBaseURL.setText(actualCustomServer); + + AlertDialog.Builder urlAlert = new AlertDialog.Builder(activity); + urlAlert.setTitle(context.getResources() + .getString( + R.string.server_selector_custom_server_alert_title)); + urlAlert.setView(tbBaseURL); + urlAlert.setPositiveButton( + context.getResources().getString(android.R.string.ok), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + Editable tbEditable = tbBaseURL.getText(); + if (tbEditable != null) { + String value = tbEditable.toString().trim(); + if (URLUtil.isValidUrl(value)) { + SharedPreferences.Editor prefsEditor + = PreferenceManager + .getDefaultSharedPreferences( + context) + .edit(); + prefsEditor + .putString( + PREFERENCE_KEY_CUSTOM_SERVER_URL, + value); + + ServerChecker serverChecker + = new ServerChecker(new WeakReference(activity), + context, ServerSelectorReceiver.this, true, + true, false); + serverChecker.execute( + new Server(value, context)); + prefsEditor.commit(); + } else { + Toast.makeText(context, + context.getResources() + .getString( + R.string.settings_menu_custom_server_url_description_error_url), + Toast.LENGTH_SHORT).show(); } - } - }); - selectedCustomServer = true; - urlAlert.create().show(); - } + + } + }); + selectedCustomServer = true; + urlAlert.create().show(); } else { //User picked server from the list for (Server server : knownServers) { //If this server region matches what the user picked, then set the server as the selected server if (server.getRegion().equals(items[item])) { selectedServer = server; - ServerChecker serverChecker = new ServerChecker(activity, - context, ServerSelector.this, false, false, false); + ServerChecker serverChecker = new ServerChecker(new WeakReference(activity), + context, ServerSelectorReceiver.this, false, false, false); serverChecker.execute(selectedServer); break; } @@ -449,76 +453,76 @@ public void onClick(DialogInterface dialog, } }); builder.show(); - } - } else { - Log.e(OTPApp.TAG, "Server list could not be downloaded!!"); - Toast.makeText(context, - context.getResources().getString(R.string.toast_server_selector_refresh_server_list_error), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onServerCheckerComplete(String result, boolean isCustomServer, - boolean isAutoDetected, boolean isWorking) { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); - SharedPreferences.Editor prefsEditor = prefs.edit(); - if (isCustomServer){ - if (isWorking) { - prefsEditor.putBoolean(PREFERENCE_KEY_AUTO_DETECT_SERVER, false); - prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, true); - prefsEditor.putBoolean(PREFERENCE_KEY_CUSTOM_SERVER_URL_IS_VALID, true); - prefsEditor.commit(); - if (selectedCustomServer) { - String baseURL = prefs.getString(PREFERENCE_KEY_CUSTOM_SERVER_URL, ""); - selectedServer = new Server(baseURL, context); - callback.onServerSelectorComplete(selectedServer); - } } else { - prefsEditor.putBoolean(PREFERENCE_KEY_CUSTOM_SERVER_URL_IS_VALID, false); - prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, false); - prefsEditor.commit(); + Log.e(OTPApp.TAG, "Server list could not be downloaded!!"); Toast.makeText(context, - context.getResources().getString(R.string.toast_server_checker_error_bad_url), + context.getResources().getString(R.string.toast_server_selector_refresh_server_list_error), Toast.LENGTH_SHORT).show(); } } - else{ - if (isWorking){ - if (isAutoDetected){ - long serverId = prefs.getLong(OTPApp.PREFERENCE_KEY_SELECTED_SERVER, 0); - Server s = null; - boolean serverIsChanged = true; - if (serverId != 0) { - dataSource.open(); - s = dataSource.getServer(prefs.getLong(OTPApp.PREFERENCE_KEY_SELECTED_SERVER, 0)); - dataSource.close(); - } - if (s != null) { - serverIsChanged = !(s.getRegion().equals(selectedServer.getRegion())); - } - if (showDialog || serverIsChanged) { - Toast.makeText(context, - context.getResources() - .getString(R.string.toast_server_selector_detected) + " " - + selectedServer.getRegion() + ". " + context.getResources() - .getString(R.string.toast_server_selector_server_change_info), - Toast.LENGTH_SHORT).show(); + + @Override + public void onServerCheckerComplete(String result, boolean isCustomServer, + boolean isAutoDetected, boolean isWorking) { + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + SharedPreferences.Editor prefsEditor = prefs.edit(); + if (isCustomServer){ + if (isWorking) { + prefsEditor.putBoolean(PREFERENCE_KEY_AUTO_DETECT_SERVER, false); + prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, true); + prefsEditor.putBoolean(PREFERENCE_KEY_CUSTOM_SERVER_URL_IS_VALID, true); + prefsEditor.commit(); + if (selectedCustomServer) { + String baseURL = prefs.getString(PREFERENCE_KEY_CUSTOM_SERVER_URL, ""); + selectedServer = new Server(baseURL, context); + callback.onServerSelectorComplete(selectedServer); } + } else { + prefsEditor.putBoolean(PREFERENCE_KEY_CUSTOM_SERVER_URL_IS_VALID, false); + prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, false); + prefsEditor.commit(); + Toast.makeText(context, + context.getResources().getString(R.string.toast_server_checker_error_bad_url), + Toast.LENGTH_SHORT).show(); } - prefsEditor.putLong(PREFERENCE_KEY_SELECTED_SERVER, - selectedServer.getId()); - prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, false); - prefsEditor.commit(); - callback.onServerSelectorComplete(selectedServer); } else{ - Toast.makeText(context, - context.getResources() - .getString(R.string. - toast_server_checker_error_unreachable_detected_server), - Toast.LENGTH_SHORT).show(); + if (isWorking){ + if (isAutoDetected){ + long serverId = prefs.getLong(OTPApp.PREFERENCE_KEY_SELECTED_SERVER, 0); + Server s = null; + boolean serverIsChanged = true; + if (serverId != 0) { + dataSource.open(); + s = dataSource.getServer(prefs.getLong(OTPApp.PREFERENCE_KEY_SELECTED_SERVER, 0)); + dataSource.close(); + } + if (s != null) { + serverIsChanged = !(s.getRegion().equals(selectedServer.getRegion())); + } + if (showDialog || serverIsChanged) { + Toast.makeText(context, + context.getResources() + .getString(R.string.toast_server_selector_detected) + " " + + selectedServer.getRegion() + ". " + context.getResources() + .getString(R.string.toast_server_selector_server_change_info), + Toast.LENGTH_SHORT).show(); + } + } + prefsEditor.putLong(PREFERENCE_KEY_SELECTED_SERVER, + selectedServer.getId()); + prefsEditor.putBoolean(PREFERENCE_KEY_SELECTED_CUSTOM_SERVER, false); + prefsEditor.commit(); + callback.onServerSelectorComplete(selectedServer); + } + else{ + Toast.makeText(context, + context.getResources() + .getString(R.string. + toast_server_checker_error_unreachable_detected_server), + Toast.LENGTH_SHORT).show(); + } } } }