I am currently trying to follow along this tutorial to get last location of android device - https://developer.android.com/training/location/retrieve-current.html#play-services - but I cannot get past the last part.
My code:
package com.example.prouser.driveapp;
public class MainActivity extends AppCompatActivity implements ConnectionCallbacks {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
super.onStart();
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected(Bundle connectionHint) {
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
// Create an instance of GoogleAPIClient.
GoogleApiClient mGoogleApiClient = new GoogleApiClient() {
#Override
public boolean hasConnectedApi(#NonNull Api<?> api) {
return false;
}
#NonNull
#Override
public ConnectionResult getConnectionResult(#NonNull Api<?> api) {
return null;
}
#Override
public void connect() {
}
#Override
public ConnectionResult blockingConnect() {
return null;
}
#Override
public ConnectionResult blockingConnect(long l, #NonNull TimeUnit timeUnit) {
return null;
}
#Override
public void disconnect() {
}
#Override
public void reconnect() {
}
#Override
public PendingResult<Status> clearDefaultAccountAndReconnect() {
return null;
}
#Override
public void stopAutoManage(#NonNull FragmentActivity fragmentActivity) {
}
#Override
public boolean isConnected() {
return false;
}
#Override
public boolean isConnecting() {
return false;
}
#Override
public void registerConnectionCallbacks(#NonNull ConnectionCallbacks connectionCallbacks) {
}
#Override
public boolean isConnectionCallbacksRegistered(#NonNull ConnectionCallbacks connectionCallbacks) {
return false;
}
#Override
public void unregisterConnectionCallbacks(#NonNull ConnectionCallbacks connectionCallbacks) {
}
#Override
public void registerConnectionFailedListener(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
}
#Override
public boolean isConnectionFailedListenerRegistered(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
return false;
}
#Override
public void unregisterConnectionFailedListener(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
}
#Override
public void dump(String s, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strings) {
}
};
if(mGoogleApiClient==null)
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
Try this:
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected static final String TAG = "MainActivity";
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
protected String mLatitudeLabel;
protected String mLongitudeLabel;
protected TextView mLatitudeText;
protected TextView mLongitudeText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
mLastLocation.getLatitude()));
mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
mLastLocation.getLongitude()));
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
}
You have a complete example here:
https://github.com/googlesamples/android-play-location
Related
I'm trying to use the mapbox SDK to get my current location and set the navigation, but it's not working. I was trying to implement this code following the tutorial from the mapbox website.
public class pos extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
//private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaWhkaW5hIiwiYSI6ImNqaDRveHdhcjB1ZTIyd253M2R2MGhwY28ifQ.If9oJq_rILeuaK1sjp9-nw");
setContentView(R.layout.activity_pos);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
/* button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);*/
}
;
});
/*button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});*/
}
;
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Try modifying your methods with this:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
and your onStart with this:
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
locationEngine.addLocationEngineListener(this);
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!
I have code which is working fine for logout of google apiclient, but it left one activity opened after execution, either can some one tell where should I put finish(); to kill that activity or how can I do whole thing in async task. I tried to do with async but got error as client not connected.
Here is code for logout with class extending to activity:
public class GoogleDriveLogoutBackup extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.d("Connected","Here");
mGoogleApiClient.clearDefaultAccountAndReconnect();
finish();
}
#Override
public void onConnectionSuspended(int i) {
finish();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
And here is code which I m using for Async class which I giving me error:
public class GoogleDriveLogout extends AsyncTask<Void, Void, Void> {
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
private Context mcontext;
public GoogleDriveLogout(Context context) {
this.mcontext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mcontext)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected Void doInBackground(Void... params) {
Log.d("Connected", "Here");
mGoogleApiClient.clearDefaultAccountAndReconnect();
return null;
}
}
I able to did it now by using calling ApiClientAsyncTask which is provided by google itself.
I am a learner in android. I am trying to get weather on current location. There is a "Refresh" button in my app to update the UI with latest weather details. When the app loads, it shows weather of 0.0, 0.0 latitude and longitude. When I click on "Refresh" button, it shows the weather of my current location. How can I get the weather of my current location when the app loads? I have used Google Play Services to get the current location. Below is my code.
MainActivity.java
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public String apiKey;
public double latitude;
public double longitude;
public String forecastUrl;
public static final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
public MainActivity() {
apiKey = “XXXXXXXXXX";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void getForecast() {
if (isNetworkAvailable()) {
forecastUrl = “http://www.forecastUrlGoesHere.com/" + apiKey + “/“ + latitude + "," + longitude;
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
updateView(); //updates the screen ui
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_error_message), Toast.LENGTH_LONG).show();
}
}
private void updateView() {
//code to update ui
}
private boolean isNetworkAvailable() {
//check network availability
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
private void toggleRefresh() {
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, latitude + " " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getString(R.string.no_location_detected), Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, 9000);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Connection failed, ERROR: " + connectionResult.getErrorCode());
}
}
}
Well there are a few ways to get the expected result. Let me write the steps for one of them:
a) Use a ProgressDialog and start it in onCreate
b) Move the getForecast() from onCreate
c) In the onConnected method, once the lat and long are available, check if the ProgressDialog is still visible. If yes, dismiss this dialog and call getForecast
ProgressDialog link
http://developer.android.com/reference/android/app/ProgressDialog.html
In your onConnected callback, call getForecast();:
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, latitude + " " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getString(R.string.no_location_detected), Toast.LENGTH_LONG).show();
}
getForecast();
}
In my activity i am implementing the below given classes
com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks,
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks,
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
These two interfaces is for authenticating user through google plus.
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks,
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
and these are for getting user current location
com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks,
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener
the methods have in these classes are same.
#Override
public void onConnected(Bundle connectionHint) {}
and
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
Since these methods have the same parameters and same return type i cant have two in the same class. So i think i need to identify which interface have invoked from the Bundle or ConnectionResult . How i can do this ? I mean which key value i need to check ? If need any clarification please comment.
Thank you
What about implementing the interfaces as a anonymous member declaration ?
public class Ac {
private GooglePlayServicesClient.OnConnectionFailedListener psConnectionFailedListener =
new GooglePlayServicesClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// implementation
}
};
private GooglePlayServicesClient.ConnectionCallbacks psConnectionCallbacks =
new GooglePlayServicesClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
// implementation
}
#Override
public void onDisconnected() {
// implementation
}
};
private GoogleApiClient.ConnectionCallbacks googleConnectionCallbacks =
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
// implementation
}
#Override
public void onConnectionSuspended(int i) {
// implementation
}
};
private GoogleApiClient.OnConnectionFailedListener googleConnectionFailedListener =
new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// implementation
}
};
}