Login Issue in Amazon Mobile Hub with Cognito - facebook

I am using Mobile Hub (amazon) in my android project and for sign-in providers i am using cognito and I have their sample code which they provide and I modify the code and the Login with Facebook is working but the issue which I am facing is onSuccess method when user login successfully called twice and I debugg it but I can not Figure it out how to fix that issue.
SplashActivity.java
public class SplashActivity extends AppCompatActivity implements SignInResultHandler {
IdentityManager identityManager;
private LottieAnimationView animationView;
private static final String LOG_TAG = SplashActivity.class.getSimpleName() + " : ";
private final StartupAuthResultHandler authResultHandler = new StartupAuthResultHandler() {
#Override
public void onComplete(final StartupAuthResult authResult) {
identityManager = authResult.getIdentityManager();
if (authResult.isUserSignedIn()) {
// User has successfully signed in with an identity provider.
final IdentityProvider provider = identityManager.getCurrentIdentityProvider();
Logger.d(LOG_TAG + "Signed in with " + provider.getDisplayName());
} else if (authResult.isUserAnonymous()) {
// User has an unauthenticated anonymous (guest) identity, either because the user never previously
// signed in with any identity provider or because refreshing the provider credentials failed.
// Optionally, you can check whether refreshing a previously signed in provider failed.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
if (errors.didErrorOccurRefreshingProvider()) {
final AuthException providerAuthException = errors.getProviderRefreshException();
Logger.d(LOG_TAG + String.format(
"Credentials for Previously signed-in provider %s could not be refreshed." +
providerAuthException.getProvider().getDisplayName()) +
providerAuthException);
}
Logger.d(LOG_TAG + "Continuing with unauthenticated (guest) identity.");
} else {
// User has no identity because authentication was unsuccessful due to a failure.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
Logger.e(LOG_TAG + "No Identity could be obtained. Continuing with no identity.",
errors.getUnauthenticatedErrorException());
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
animationView = (LottieAnimationView) findViewById(R.id.animation_view);
identityManager = AWSMobileClient.defaultMobileClient().getIdentityManager();
identityManager.doStartupAuth(this, authResultHandler);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (identityManager.isUserSignedIn()) {
goMain();
} else {
goSignIn();
}
}
}, 2000);
}
#Override
public void onStart() {
super.onStart();
animationView.setProgress(0f);
animationView.playAnimation();
}
#Override
public void onStop() {
super.onStop();
animationView.cancelAnimation();
}
/**
* Go to the main activity.
*/
private void goMain() {
startActivity(new Intent(this, MainActivity.class));
}
private void goSignIn() {
identityManager.signInOrSignUp(this, this);
finish();
}
/* This method is called two times and I also search in code it inoke only one time*/
#Override
public void onSuccess(Activity callingActivity, IdentityProvider provider) {
callingActivity.finish();
if(provider != null) {
IdentityProfile identityProfile = identityManager.getIdentityProfile();
Logger.d(LOG_TAG + " Name : " + identityProfile.getUserName());
Logger.d(LOG_TAG + " Email : " + identityProfile.getUserEmailAddress());
Logger.d(LOG_TAG + " ImageLink : " + identityProfile.getUserImageUrl());
Logger.d(LOG_TAG + " provider : " + provider.getProviderType());
}
goMain();
}
/**
* User cancelled signing in with a provider on the sign-in activity.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user canceled with.
*/
public void onIntermediateProviderCancel(Activity callingActivity, IdentityProvider provider) {
Logger.d(LOG_TAG + "onIntermediateProviderCancel() called with: callingActivity = " +
"[" + callingActivity + "], provider = [" + provider + "]");
}
/**
* User encountered an error when attempting to sign-in with a provider.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user attempted to sign-in with that encountered an error.
* #param ex the exception that occurred.
*/
public void onIntermediateProviderError(Activity callingActivity, IdentityProvider provider, Exception ex) {
Logger.d(LOG_TAG + "onIntermediateProviderError() called with: callingActivity = [" + callingActivity + "], " +
"provider = [" + provider + "], errorMesage = [" + ex.getMessage() + "]");
}
#Override
public boolean onCancel(Activity callingActivity) {
return false;
}
}
SignInActivity.java
public class SignInActivity extends AppCompatActivity {
private static final String LOG_TAG = SignInActivity.class.getSimpleName() + " : ";
private SignInManager signInManager;
/**
* SignInProviderResultHandlerImpl handles the final result from sign in.
*/
private class SignInProviderResultHandlerImpl implements SignInProviderResultHandler {
/**
* Receives the successful sign-in result and starts the main activity.
*
* #param provider the identity provider used for sign-in.
*/
#Override
public void onSuccess(final IdentityProvider provider) {
Logger.d(LOG_TAG + String.format("Sign-in with %s succeeded.", provider.getDisplayName()));
// The sign-in manager is no longer needed once signed in.
SignInManager.dispose();
final IdentityManager identityManager = signInManager.getIdentityManager();
final SignInResultHandler signInResultsHandler = signInManager.getResultHandler();
// Load user name and image.
identityManager.loadUserIdentityProfile(provider, new Runnable() {
#Override
public void run() {
// Call back the results handler.
signInResultsHandler.onSuccess(SignInActivity.this, provider);
finish();
}
});
}
/**
* Receives the sign-in result indicating the user canceled and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
*/
#Override
public void onCancel(final IdentityProvider provider) {
Logger.i(LOG_TAG + String.format("Sign-in with %s canceled.", provider.getDisplayName()));
signInManager.getResultHandler().onIntermediateProviderCancel(SignInActivity.this, provider);
}
/**
* Receives the sign-in result that an error occurred signing in and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
* #param ex the exception that occurred.
*/
#Override
public void onError(final IdentityProvider provider, final Exception ex) {
Logger.d(LOG_TAG + String.format("Sign-in with %s caused an error." +
provider.getDisplayName()) + ex);
signInManager.getResultHandler().onIntermediateProviderError(SignInActivity.this, provider, ex);
}
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> readPermissions = new ArrayList<>();
readPermissions.add("public_profile");
readPermissions.add("email");
loginButton.setReadPermissions(readPermissions);
signInManager = SignInManager.getInstance();
signInManager.setProviderResultsHandler(this, new SignInProviderResultHandlerImpl());
signInManager.initializeSignInButton(IdentityProviderType.FACEBOOK, loginButton);
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String permissions[],
#NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
signInManager.handleRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
signInManager.handleActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (signInManager != null) {
if (signInManager.getResultHandler().onCancel(this)) {
super.onBackPressed();
// Since we are leaving sign-in via back, we can dispose the sign-in manager, since sign-in was cancelled.
SignInManager.dispose();
}
}
finish();
}
}

Related

Background service is not working in some devices like vivo , mi etc.. after app is clear from recent app

i am use the below code to send the location to the server but it is not working in some devices after app is clear from recent app. so what is best alternate way to start service when app is closed.
public class GpsService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private LocationCallback mLocationCallback;
SharePref sharePref;
#Override
public void onCreate() {
super.onCreate();
Log.e("sevice start", ">>>>>>>>>>>>>>>>>>>>>>>>>......");
sharePref = new SharePref(GpsService.this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
Toast.makeText(getBaseContext(), locationResult.toString(), Toast.LENGTH_LONG).show();
}
}
;
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("sevice start", "mGoogleApiClient >>>>>>>>>>>>>>>>>>>>>>>>>......");
mGoogleApiClient.connect();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
//Save your location
Log.e("GpsService Location lat", "Is change " + location.getLatitude());
Log.e("Gps Location long", "Is change " + location.getLongitude());
Log.e("GpsService userid", "Enter" + sharePref.getUserId());
Toast.makeText(GpsService.this, location.toString(), Toast.LENGTH_LONG).show();
sharePref.SetLat(String.valueOf(location.getLatitude()));
sharePref.SetLong(String.valueOf(location.getLongitude()));
String lati = String.valueOf(location.getLatitude());
String longi = String.valueOf(location.getLongitude());
HashMap<String, String> param = new HashMap<>();
param.put(PARAM_USER_ID, sharePref.getUserId());
param.put(PARAM_SESSION_ID, sharePref.getSessionId());
param.put(PARAM_LAT, lati);
param.put(PARAM_LONG, longi);
param.put(PARAM_PLATFORM, PLATFORM);
BikerService.addLatLong(GpsService.this, param, new APIService.Success<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
Log.e("Location Response-->", "" + response.toString());
BikerParser.AddLatLongResponse AddLatLongResponse = BikerParser.AddLatLongResponse.addLatLongResponse(response);
if (AddLatLongResponse.getStatusCode() == API_STATUS_FOUR_ZERO_ONE) {
stopService(new Intent(GpsService.this, GpsService.class));
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.e("sevice start", "startLocationUpdates >>>>>>>>>>>>>>>>>>>>>>>>>......");
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
}

how to watch the cilent when it lose Leadership through zookeeper curator?

as we know,when the client get the leadership,will invode the takeLeadership,but the document do not tell me when the client lost the leadership!!!so,how to watch the cilent when it lose Leadership through zookeeper curator?
question two : why my client was lose,i am can not debug the stateChanged(...) thought idea?
here my code, expect your great answer,thx
public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable{
private final String name;
private final LeaderSelector leaderSelector;
private final AtomicInteger leaderCount = new AtomicInteger();//用于记录领导次数
public ExampleClient(CuratorFramework client,String path,String name) {
this.name = name;
leaderSelector = new LeaderSelector(client, path, this);
leaderSelector.autoRequeue();//保留重新获取领导权资格
}
public void start() throws IOException {
leaderSelector.start();
}
#Override
public void close() throws IOException {
leaderSelector.close();
}
#Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) {
log.info("stateChanged !!!");
throw new CancelLeadershipException();
}
}
/**
* will be invoded when get leadeship
* #param client
* #throws Exception
*/
#Override
public void takeLeadership(CuratorFramework client) throws Exception {
final int waitSeconds =(int)(Math.random()*5)+1;
log.info(name + " is the leader now,wait " + waitSeconds + " seconds!");
log.info(name + " had been leader for " + leaderCount.getAndIncrement() + " time(s) before");
try {
/**/
Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));
//do something!!!
/*while(true){
//guarantee this client be the leader all the time!
}*/
}catch (InterruptedException e){
log.info(name+" was interrupted!");
Thread.currentThread().interrupt();
}finally{
log.info(name+" relinquishing leadership.\n");
}
}
}
LeaderLatchListener has two call backs about isLeader and notLeader. Some examples,
http://www.programcreek.com/java-api-examples/index.php?api=org.apache.curator.framework.recipes.leader.LeaderLatchListener

current location not display accurately by google location API

When I am running this code it gives current location after I clicked the button_currentlocation. But when I checked the accuracy it is very low accuracy (sometime 5000m). But I need to get current location for one time with high accuracy (around 10m).
If someone can help me to correct my coding,it will be great help for my research.
My cordings are as follow
in my manifest
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
LocationProvider Class
public class LocationProvider implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
In HomePage Class
package com.ksfr.finaltest01;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
public class HomePage extends Activity implements AdapterView.OnItemSelectedListener,LocationProvider.LocationCallback {
public static final String TAG = HomePage.class.getSimpleName();
Button button_disFinder;
private LocationProvider locationProvider;
String Provider,Str_endLocation;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
locationProvider = new LocationProvider(this,this);
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.school_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void CurrentLocationClicked(View view) {
if (cur_latitude!=0&&cur_longitude != 0 ){
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
spinner.setClickable(true);
String message= String.format("Current Location\n" + "Latitude :" + cur_latitude + "\nLongitude :" + cur_longitude+"\nAccuracy :"+cur_accuracy+"\nProvider :"+Provider);
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
}
else{
String message= String.format("Location services disconnected.\nSwich ON Location Service to work App.");
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
//System.exit(0);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!= 0) {
Str_endLocation=String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), Str_endLocation + " Selected", Toast.LENGTH_SHORT).show();
switch (Str_endLocation){
//end location latitude and logitude will be taken from here.
case "Kahagolla National School":
end_latitude = 6.816703;end_longitude = 80.9637076;
break;
}
String message3= String.format("End Location\n"+"Latitude :"+end_latitude+"\nLongitude :"+end_longitude);//For Testing
Toast.makeText(HomePage.this, message3, Toast.LENGTH_LONG).show();//For Testing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void FindDistanceClicked (View view){
Location curlocation = new Location("");
curlocation.setLatitude(cur_latitude);
curlocation.setLongitude(cur_longitude);
Location endlocation = new Location("");
endlocation.setLatitude(end_latitude);
endlocation.setLongitude(end_longitude);
distance_cur_to_end = curlocation.distanceTo(endlocation)/1000;
String message5= String.format("Distance from current location to\n" + Str_endLocation + " :" + String.format("%.3g%n", distance_cur_to_end)+"km");//For testing
Toast.makeText(HomePage.this, message5, Toast.LENGTH_LONG).show();//For testing
}
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
LatLng cur_latLng = new LatLng(cur_latitude, cur_longitude);
}
#Override
protected void onResume() {
super.onResume();
locationProvider.connect();
}
#Override
protected void onPause() {
super.onPause();
locationProvider.disconnect();
}
public void ClearClicked (View view){
}
}
Try reversing your onConnected method location code.
First try to get current location and if that is not available then try getting lastKnown location.
Some thing like this
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
I corrected my issue finally,
From this method i got locations in 3m accuracy,which I want.
Here's code
DistanceFinderActivity.java
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5*1000; // in Milliseconds
protected LocationManager locationManager;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
public LatLng cur_latLng,end_latLng;
MyLocationListener myLocationListener =new MyLocationListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_distance_finder);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
myLocationListener
);
//......
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(GPS_PROVIDER);
if (location != null) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"Current Location \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s\nWait until new location capture",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)),Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"New Location Captured. \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)), Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainDistanceFinderActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}

google cloud print from android without dialog

Can someone tell me if it is possible to silently print using google cloud print from an android device?
The goal is that my app grabs a file from a URL or from the SD card and then sends it to a specific printer - all without interaction from anyone looking at the screen or touching anything. It will actually be triggered by a barcode scan on a blue tooth connected device.
Thanks
Well, it is possible but I don't know why there's not too much information about it in the documentation...
The tricky part is connecting to the google cloud print API using only the android device (with no third party servers as the documentation explains here: https://developers.google.com/cloud-print/docs/appDevGuide ), so that's what I'm going to explain.
First, you have to include in your app the Google sign-in API, I recommend firebase API https://firebase.google.com/docs/auth/android/google-signin
Then you have to go to your Google API console: https://console.developers.google.com in the menu, go to Credentials scroll to OAuth 2.0 client IDs select Web client (auto created by Google Service) and save into your project the Client ID and Client secret keys... In my project, I saved them as "gg_client_web_id" and "gg_client_web_secret" as you will see below in the code.
Next, I'm going to paste all the code and then I'll explain it:
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final int REQUEST_SINGIN = 1;
private TextView txt;
public static final String TAG = "mysupertag";
public static final String URLBASE = "https://www.google.com/cloudprint/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
mAuth = FirebaseAuth.getInstance();
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.gg_client_web_id))
.requestEmail()
.requestServerAuthCode(getString(R.string.gg_client_web_id))
.requestScopes(new Scope("https://www.googleapis.com/auth/cloudprint"))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "error connecting: " + connectionResult.getErrorMessage());
Toast.makeText(this, "error CONN", Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == REQUEST_SINGIN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, "error ", Toast.LENGTH_LONG).show();
}
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQUEST_SINGIN);
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
FirebaseUser user = task.getResult().getUser();
txt.setText(user.getDisplayName() + "\n" + user.getEmail());//todo
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
getAccess(acct.getServerAuthCode());
}
});
}
private void getPrinters(String token) {
Log.d(TAG, "TOKEN: " + token);
String url = URLBASE + "search";
Ion.with(this)
.load("GET", url)
.addHeader("Authorization", "Bearer " + token)
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "finished " + result.getHeaders().code() + ": " +
result.getResult());
if (e == null) {
Log.d(TAG, "nice");
} else {
Log.d(TAG, "error");
}
}
});
}
private void getAccess(String code) {
String url = "https://www.googleapis.com/oauth2/v4/token";
Ion.with(this)
.load("POST", url)
.setBodyParameter("client_id", getString(R.string.gg_client_web_id))
.setBodyParameter("client_secret", getString(R.string.gg_client_web_secret))
.setBodyParameter("code", code)
.setBodyParameter("grant_type", "authorization_code")
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
Log.d(TAG, "result: " + result.getResult());
if (e == null) {
try {
JSONObject json = new JSONObject(result.getResult());
getPrinters(json.getString("access_token"));
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.d(TAG, "error");
}
}
});
}}
As you can see, in the onCreate the important part is creating the GoogleSignInOptions WITH the google cloud print scope AND calling the requestIdToken/requestServerAuthCode methods.
Then in the firebaseAuthWithGoogle method call the getAccess method in order to get the OAuth access token, for making all requests I'm using Ion library: https://github.com/koush/ion
Next with the access_token you can now do requests to the google cloud print API, in this case I call the getPrinters method, in this method I call the "search" method (from google cloud print API) to get all the printers associated to the google account that has signed in.. (to associate a printer to a google account visit this: https://support.google.com/cloudprint/answer/1686197?hl=en&p=mgmt_classic ) Note the .addHeader("Authorization", "Bearer " + token), this is the important part of the request, the "token" var is the access_token, you NEED add this Authorization header in order to use the API and don't forget to refresh when it expires, as explained here : https://developers.google.com/identity/protocols/OAuth2ForDevices in the "Using a refresh token" part.
And that's it, you can now print something sending a POST request to the "submit" method of the google cloud print API, I recommend to go here: https://developers.google.com/cloud-print/docs/appInterfaces and see all the methods available and how to use them (wich parameters send to them, etc). Of course in that link explains the "submit" method too.
EDIT:
EXAMPLE OF HOW TO SEND A REQUEST TO "/submit" FOR PRINTING USING ION LIBRARY AND MJSON LIBRARY (https://bolerio.github.io/mjson/) THE MJSON IS FOR CREATING A JSON OBJECT, YOU CAN CREATE IT THE WAY YOU PREFER
private void printPdf(String pdfPath, String printerId) {
String url = URLBASE + "submit";
Ion.with(this)
.load("POST", url)
.addHeader("Authorization", "Bearer " + YOUR_ACCESS_TOKEN)
.setMultipartParameter("printerid", printerId)
.setMultipartParameter("title", "print test")
.setMultipartParameter("ticket", getTicket())
.setMultipartFile("content", "application/pdf", new File(pdfPath))
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
if (e == null) {
Log.d(TAG, "PRINTTT CODE: " + result.getHeaders().code() +
", RESPONSE: " + result.getResult());
Json j = Json.read(result.getResult());
if (j.at("success").asBoolean()) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
Log.d(TAG, e.toString());
}
}
});
}
private String getTicket() {
Json ticket = Json.object();
Json print = Json.object();
ticket.set("version", "1.0");
print.set("vendor_ticket_item", Json.array());
print.set("color", Json.object("type", "STANDARD_MONOCHROME"));
print.set("copies", Json.object("copies", 1));
ticket.set("print", print);
return ticket.toString();
}
Yes, You can achieve silent print using this REST API(https://www.google.com/cloudprint/submit) ,I have done it using WCF Service.
you need to download contents from url as base64 content, then add
contentType=dataUrl
in the request.
Here is the code..
postData = "printerid=" + PrinterId;
postData += "&title=" + JobTitle;
postData += "&ticket=" + ticket;
postData += "&content=data:" + documentContent.ContentType + ";base64," + documentContent.Base64Content;
postData += "&contentType=dataUrl";
postData += "&tag=test";
Then , please make a request to submit REST API in this way.
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com/cloudprint/submit");
var data = Encoding.ASCII.GetBytes(postData);
request.Headers.Add("Authorization: Bearer " + Token);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.UseDefaultCredentials = true;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
PrintJobResponse printInfo = json_serializer.Deserialize<PrintJobResponse>(responseString);
return printInfo;
Thanks.
For anybody reading this now, after a lot of searching around I have found it is a lot easier and faster to set up to just use Zapier to catch a hook and print to google cloud print (from cordova at least, i can't speak for native apps)

How to integrate oauth with gwt?

Here is my code, how do I use oauth to get the data such as user_id or first and last name of the user and sign them to fields? Should I implement them in the onSuccess method?
private void addFacebookAuth(){
loginButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(FACEBOOK_AUTH_URL, FACEBOOK_APP_ID).withScopes(
FACEBOOK_EMAIL_SCOPE,
FACEBOOK_BIRTHDAY_SCOPE,
FACEBOOK_USERID_SCOPE,
FACEBOOK_USER_LAST_NAME_SCOPE,
FACEBOOK_USER_FIRST_NAME_SCOPE).withScopeDelimiter(",");
AUTH.login(req, new Callback<String, Throwable>(){
#Override
public void onFailure(Throwable reason) {
Window.alert("Error:\n" + reason.getMessage());
}
#Override
public void onSuccess(String token) {
// Window.alert("Got an OAuth token:\n" + token + "\n"
// + "Token expires in " + AUTH.expiresIn(req) + " ms\n");
RootPanel.get().remove(loginButton);
}
});
}
});
RootPanel.get().add(loginButton);
}