Skip to content
This repository has been archived by the owner on May 27, 2024. It is now read-only.

convert AsyncTasks to IntentService #472

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions opentripplanner-android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
android:theme="@style/MyTheme"
android:windowSoftInputMode="stateHidden"></activity>

<service android:name=".tasks.MetadataRequest" android:exported="false"/>
<service android:name=".tasks.OTPGeocoding" android:exported="false"/>
<service android:name=".tasks.ServerSelector" android:exported="false"/>

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyD5XadJhAK7jIKFz5TcT7t-gsWw_OTvlBI"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2087,11 +2122,16 @@ public void runAutoDetectServer(LatLng mCurrentLatLng, boolean showDialog) {
Toast.LENGTH_LONG).show();
} else {
ServersDataSource dataSource = ServersDataSource.getInstance(mApplicationContext);
WeakReference<Activity> weakContext = new WeakReference<Activity>(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);
Expand All @@ -2108,13 +2148,16 @@ public void runAutoDetectServer(LatLng mCurrentLatLng, boolean showDialog) {
*/
public void runAutoDetectServerNoLocation(boolean showDialog) {
ServersDataSource dataSource = ServersDataSource.getInstance(mApplicationContext);
WeakReference<Activity> weakContext = new WeakReference<Activity>(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);
}
Expand Down Expand Up @@ -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<Activity> weakContext = new WeakReference<Activity>(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()
Expand All @@ -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);
}
}

Expand Down Expand Up @@ -2651,9 +2703,11 @@ public void updateSelectedServer(boolean updateUI) {
WeakReference<Activity> weakContext = new WeakReference<Activity>(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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -41,52 +45,22 @@
/**
* @author Khoa Tran
*/
public class MetadataRequest extends IntentService {
ObjectMapper mapper;

public class MetadataRequest extends AsyncTask<String, Integer, GraphMetadata> {

private ProgressDialog progressDialog;

private WeakReference<Activity> activity;

private Context context;

private MetadataRequestCompleteListener callback;

private static ObjectMapper mapper = null;

public MetadataRequest(WeakReference<Activity> 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) {
Expand All @@ -106,30 +80,58 @@ 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();
}
} 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!");
}
}
}
}

Loading