Why is FirebaseInstanceIdService.onTokenRefresh() is never called? - android

Maybe I am doing a wrong step. I have 3 activities:
Launcher
Login
MainActivity
In the onCreate of my MainActivity, I am calling the service:
void iniciarServicioSendTokenFCM(){
servicioFCM= new Intent(this, IDService.class);
startService(servicioFCM);
}
And this is executed, because it gets to enter in onCreate of Service but onTokenRefresh() is never executed.
I have done these steps too. I have uninstalled and reinstalled the app but it didn't work.
public class IDService extends FirebaseInstanceIdService {
private ConnectionStatusSync ConnSync;//= new ConnectionStatusSync(this);
private DispositivoSync Sync;
private Integer dispositivoId;
private PreferenceUtil preferenceUtil ;
private String tokenDispositivo;
private DispositivoSync.OnFragmentInteractionListener listener;
public IDService() {
}
#Override
public void onCreate() {
super.onCreate();
Listener();
ConnSync = new ConnectionStatusSync(this);
Sync = new DispositivoSync(this);
preferenceUtil= new PreferenceUtil(this);
dispositivoId=preferenceUtil.getInt(getString(R.string.dispositivoID),0,null);
dispositivoId=(dispositivoId==0?null:dispositivoId);
tokenDispositivo= new IDUtil(this).getId();
}
private void Listener(){
listener = new DispositivoSync.OnFragmentInteractionListener() {
#Override
public void onFinished(boolean terminoBien, int dispositivoID) {
if(terminoBien){
preferenceUtil.savePreference(getString(R.string.dispositivoID),dispositivoID,null);
}
}
};
}
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
preferenceUtil.savePreference(getString(R.string.TokenFCM),refreshedToken,null);
//Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
if(validaciones())
sendRegistrationToServer(refreshedToken);
}
private boolean validaciones(){
return dispositivoId!=null && MainActivity.mOperador!=null;
}
private void sendRegistrationToServer(final String token){
final Thread registrar = new Thread(new Runnable() {
#Override
public void run() {
Sync.EnviarDispositivo(MainActivity.mOperador.getOperadorIdServidor(),dispositivoId,token,tokenDispositivo,listener );
}
});
Thread hilo = new Thread(new Runnable() {
#Override
public void run() {
Command commandNull= new Command() {
#Override
public void execute() {
}
};
ConnSync.CheckConnection(registrar,commandNull);
}
});
hilo.start();
}
}

In an app that uses Firebase Cloud Messaging, the client immediately starts generating the token when the app starts.
Most likely the initial token has already been generated by the time you start listening for onTokenRefresh(). So you'll want to also immediately request and store the token in your iniciarServicioSendTokenFCM method:
sendRegistrationToServer(FirebaseInstanceId.getInstance().getToken());
I don't think it is very useful to store the token in shared preferences by the way, given that it is readily accessible from FirebaseInstanceId.getInstance().getToken().

Related

Firebase token in URL

I've followed this method to send my fcm token in the URL.
Following is my custom launcher activity
public class LauncherActivity
extends com.google.androidbrowserhelper.trusted.LauncherActivity {
private String fcmToken;
#Override
protected Uri getLaunchingUrl() {
Uri uri = super.getLaunchingUrl();
return uri
.buildUpon()
.appendQueryParameter("fcmToken", fcmToken)
.build();
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
return;
}
fcmToken = task.getResult();
launchTwa();
}
});
}
#Override
protected boolean shouldLaunchImmediately() {
return false;
}
Problem is when i run the app for the first time it get stuck in the splash screen.Then after killing the app , second time onward it works.
This issues is discussed in here as well , but with no luck.Any help will be appreciated.
Since i didn't find and resolution to this , following is the way i found to overcome this issue.Now i don't have the stuck in initial step and already token is passed to my server.
LauncherActivity.java
public class LauncherActivity
extends com.google.androidbrowserhelper.trusted.LauncherActivity {
private String fcmToken;
#Override
protected Uri getLaunchingUrl() {
uri = super.getLaunchingUrl();
return uri
.buildUpon()
.appendQueryParameter("fcmToken", fcmToken)
.build();
}
#Override
protected boolean shouldLaunchImmediately() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
fcmToken = preferences.getString("fcmTokenNew", "");
Boolean res = false;
if(fcmToken != null && !fcmToken.trim().isEmpty()) {
res = true;
}
return res;
}
}
CustomFirebaseMessagingService.java
public class CustomFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String token) {
sendToSariroti(token);
}
protected void sendToServer(String fcmToken) {
try {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("fcmTokenNew",fcmToken);
editor.apply();
Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(
getBaseContext().getPackageName() );
intent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is happening is when you first launch the app,
It checks whether the parameter(fcmToken) is not null/available inside shouldLaunchImmediately If it's available , no problem , continue with launching the app
If token not available stop launching the app
Inside onNewToken , it watches until token is received from Firebase.
After it received it will call sendToServer.
Inside sendToServer, it store the fcmToken in shared preference and re-launch the app again.
Hope this will help to someone.
This issue has been handled in version 2.2.2 of android-browser-helper. For versions before that you can call onEnterAnimationComplete() after calling launchTwa(). You can find more info about this workaround here

FCM Token Issue

I had UrbanAirship implemented in version 1 of the app.
Now I extended FirebaseMessagingService in version 2 of the app.
I am not getting a call in onNewToken() to be able to send the token to my servers.
My boilerplate code looks like
AndroidManifest.xml
<service
android:name=".services.fcm.PushMessageReceiver"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and Receiver
public class PushMessageReceiver extends FirebaseMessagingService { ...
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
...
}
#Override
public void onNewToken(String s) {
Log.i(Config.LOGTAG, "######**** new token for fcm called");
Context ctx =ApplicationCustom.getContext();
SharedPreferences preferences = ctx.getSharedPreferences(Config.SHARED_PREFERENCES, Context.MODE_PRIVATE);
preferences.edit().putString(Config.SHARED_PREFS_DEVICE_TOKEN, s).apply();
Intent intent = new Intent(this, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_FCM_TOKEN_REFRESH);
intent.putExtra("token", s);
startService(intent);
pushToServer();
}
public static void getToken() {
Log.i(Config.LOGTAG, "######**** get token for fcm called");
try {
Log.i(Config.LOGTAG, "######**** delete token for fcm called");
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getInstanceId();
} catch (IOException e) {
e.printStackTrace();
Log.w(Config.LOGTAG, "######**** delete InstanceId failed", e);
}
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(task
-> {
if (!task.isSuccessful()) {
Log.w(Config.LOGTAG, "getInstanceId failed", task.getException());
return;
}
Log.i(Config.LOGTAG, "######**** getInstanceId successful");
// Get new Instance ID token
String token = task.getResult().getToken();
Context ctx = ApplicationCustom.getContext();
SharedPreferences preferences = ctx.getSharedPreferences(Config.SHARED_PREFERENCES, Context.MODE_PRIVATE);
preferences.edit().putString(Config.SHARED_PREFS_DEVICE_TOKEN, token).apply();
pushToServer();
});
}
public void pushToServer(){
// Logic to push token to a server reading from preferences
}
}
Observations:
1) onNewToken never gets called for apps that are being updated.
2) new installs get a token
3) after I added a call to FirebaseInstanceId.getInstance().deleteInstanceId()
OnComplete does not get called either.
4) A call to getToken(senderId, "FCM") on real phones (not emulators) invariably results in
java.io.IOException: TOO_MANY_REGISTRATIONS
at com.google.firebase.iid.zzr.zza(Unknown Source:66)
at com.google.firebase.iid.zzr.zza(Unknown Source:79)
at com.google.firebase.iid.zzu.then(Unknown Source:4)
at com.google.android.gms.tasks.zzd.run(Unknown Source:5)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
how do I fix observation 1. Is it because the token has already been delivered to UrbanAirship that onNewToken does not get called?
Fyi getToken is called in a service onCreate() method.
implementation 'com.google.firebase:firebase-messaging:17.3.4'
you can get fcm token by this:-
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String firebaseToken = task.getResult().getToken();
} else {
getFirebaseToken();
}
}
});
That's okay if your onNewToken() is not called. You can get the latest token already made by firebase for your device. onNewToken() is called on specific occasions.
The registration token may change when:
-The app deletes Instance ID
-The app is restored on a new device
-The user uninstalls/reinstall the app
-The user clears app data.
Do read the firebase documentation :
https://firebase.google.com/docs/cloud-messaging/android/client#retrieve-the-current-registration-token
And for your second query, deleteInstanceId is a blocking call, so you will have to do it in a background thread. like this,
new Thread(new Runnable() {
#Override
public void run() {
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Some time onTokenRefresh() method call with some delay and it will generate token when new install happen that how its behave their for we need to implement functionality like below to overcome those issue maintain new user login also
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private String TAG = getClass().getName();
public static final String TOKEN_BROADCAST = "myfcmtokenbroadcast";
#Override
public void onTokenRefresh() {
//For registration of token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//To displaying token on logcat
Log.d("TOKEN: ", refreshedToken);
//calling the method store token and passing token
getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
storeToken(refreshedToken);
}
private void storeToken(String token) {
//we will save the token in sharedpreferences later
SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
}
In your onCreate method in MainActivity class call this methord
private void registerFCMToken(){
registerReceiver(broadcastReceiver, new IntentFilter(MyFirebaseInstanceIDService.TOKEN_BROADCAST));
final boolean isRegisterFcm = preferences.getBoolean("IS_REGISTER_FCM", false);
// FCM token Register when onTokenRefresh method call
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String fcmToken = SharedPrefManager.getInstance(MainActivity.this).getDeviceToken();
if(!isRegisterFcm) {
RegisterFcmTokenRequest request = new RegisterFcmTokenRequest();
request.setFcmtoken(fcmToken);
performRegisterFcmRequest(request);
}
}
};
// FCM token Register when new user Login
if(SharedPrefManager.getInstance(this).getDeviceToken() != null && !isRegisterFcm) {
String fcmToken = SharedPrefManager.getInstance(MainActivity.this).getDeviceToken();
RegisterFcmTokenRequest request = new RegisterFcmTokenRequest();
request.setFcmtoken(fcmToken);
performRegisterFcmRequest(request);
}
}
In the onDestroy method
unregisterReceiver(broadcastReceiver);
This class maintains the Shredpreferance for FCM token
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "FCMSharedPref";
private static final String TAG_TOKEN = "tagtoken";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//this method will save the device token to shared preferences
public boolean saveDeviceToken(String token){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TAG_TOKEN, token);
editor.apply();
return true;
}
//this method will fetch the device token from shared preferences
public String getDeviceToken(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(TAG_TOKEN, null);
}
}

How to get AWS credentials from Identity Pools (Federated Identities) with android

I am new to AWS Cognito.
From my program, I want to get AWS temporary credentials to access API services such as api from API gateway. What I have is "IdentityPoolId", "IdentityId" and "OpenIdToken".
When I tried accessing with AWS Credential by getCredentialsForIdentity, I got "Identity 'ap-northeast-1:xxxx' not found." at onError method everytimes. Please help me what I was wrong?
Single<GetCredentialsForIdentityResult> primeSingle = Single.fromCallable(MyClass::getResult);
primeSingle
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<GetCredentialsForIdentityResult>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onSuccess(#NonNull GetCredentialsForIdentityResult result) {
Credentials credentials = result.getCredentials();
}
#Override
public void onError(#NonNull Throwable e) {
Log.d("Test", "onError: " + e.getMessage());
}
});
Here is getting Credential Result code.
private static GetCredentialsForIdentityResult getResult() {
AmazonCognitoIdentity identityClient = new AmazonCognitoIdentityClient(new AnonymousAWSCredentials());
Map<String, String> logins = new HashMap<String, String>();
logins.put("cognito-identity.amazonaws.com", MyClass.OPEN_ID_TOKEN);
GetCredentialsForIdentityRequest getCredentialsForIdentityRequest =
new GetCredentialsForIdentityRequest()
.withIdentityId(MyClass.IDENTITY_ID) // Not Identity Pool Id
.withLogins(logins);
getCredentialsForIdentityRequest.setIdentityId(identityId);
GetCredentialsForIdentityResult result = identityClient.getCredentialsForIdentity(getCredentialsForIdentityRequest);
return result;
}
Finally, I got Credentials by referencing this.
https://docs.aws.amazon.com/cognito/latest/developerguide/developer-authenticated-identities.html
Thanks in advance.
Here is the code:
public class DeveloperAuthenticationProvider extends AWSAbstractCognitoDeveloperIdentityProvider {
private static final String developerProvider = null;
public DeveloperAuthenticationProvider(String identityPoolId, Regions region) {
super(null, identityPoolId, region);
// Initialize any other objects needed here.
}
// Return the developer provider name which you choose while setting up the
// identity pool in the &COG; Console
#Override
public String getProviderName() {
return developerProvider;
}
// Use the refresh method to communicate with your backend to get an
// identityId and token.
#Override
public String refresh() {
// Override the existing token
setToken(null);
// Get the identityId and token by making a call to your backend
// (Call to your backend)
// Call the update method with updated identityId and token to make sure
// these are ready to be used from Credentials Provider.
update(identityId, token);
return token;
}
// If the app has a valid identityId return it, otherwise get a valid
// identityId from your backend.
#Override
public String getIdentityId() {
// Load the identityId from the cache
identityId = "ap-northeast-1:xxxx";
return identityId;
}}
Call above call from one method:
private static AWSSessionCredentials getResult(Context context) {
DeveloperAuthenticationProvider developerProvider =
new DeveloperAuthenticationProvider("ap-northeast-1:your_pool_id", Regions.AP_NORTHEAST_1);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( context, developerProvider, Regions.AP_NORTHEAST_1);
return credentialsProvider.getCredentials();
}
And use rxjava to get response:
Single<AWSSessionCredentials> primeSingle = Single.fromCallable(() -> getResult(this));
primeSingle
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<AWSSessionCredentials>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onSuccess(#NonNull AWSSessionCredentials result) {
String secretKey = result.getAWSSecretKey();
}
#Override
public void onError(#NonNull Throwable e) {
Log.d("Test", "onError: " + e.getMessage());
}
});
After successful, you can get Credentials from onSuccess method.

how to set up cognito identity pool in android?

I am completely new to aws cognito, and these guides are all over the place and i am kind of lost. In my aws account i have made an identity pool, and now i want to try to create a new user from my android app, but it fails to create user or fails to connect to the cognito pool. I am not sure if i am doing this write and hope for your guidance!
Here is what i have so far.
public class aws extends AppCompatActivity
{
private EditText firstName,lastName,email,password;
private Button loginButton;
private String poolId,clientId,clientSecret;
CognitoUserPool userPool;
CognitoUserAttributes userAttributes;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider(
getApplicationContext(), // Context
"IDENTITY POOL_ID", // Identity Pool ID
MY_REGION // Region
);
CognitoSyncManager syncClient = new CognitoSyncManager(
getApplicationContext(), // Context
MY_REGION, // Region
credentialsProvider
);
Dataset dataset = syncClient.openOrCreateDataset("myDataset");
dataset.put("myKey", "myValue");
dataset.synchronize(new DefaultSyncCallback() {
#Override
public void onSuccess(Dataset dataset, List newRecords) {
//Your handler code here
}
});
poolId = "MY_POOL_ID";
clientId = "MY_CLIENT_ID";
clientSecret = "MY_CLIENT_SECRET";
ClientConfiguration clientConfiguration = new ClientConfiguration();
// Create a CognitoUserPool object to refer to your user pool
userPool = new CognitoUserPool(getBaseContext(), poolId, clientId, clientSecret, clientConfiguration);
bindActivity();
}
private void bindActivity()
{
firstName = (EditText) findViewById(R.id.register_firstNameET);
lastName = (EditText) findViewById(R.id.register_lastNameET);
email = (EditText) findViewById(R.id.register_emailET);
password = (EditText) findViewById(R.id.register_passwordET);
loginButton = (Button) findViewById(R.id.intro_register_zivit_button);
loginButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setUpCognito();
}
});
}
private void setUpCognito()
{
// Create a CognitoUserAttributes object and add user attributes
userAttributes = new CognitoUserAttributes();
// Add the user attributes. Attributes are added as key-value pairs
// Adding user's given name.
// Note that the key is "given_name" which is the OIDC claim for given name
userAttributes.addAttribute("given_name", firstName.getText().toString());
// Adding user's lastName
userAttributes.addAttribute("family_Name", lastName.getText().toString());
// Adding user's email address
userAttributes.addAttribute("email", email.getText().toString());
setUpCognitoHandler();
}
private void setUpCognitoHandler()
{
SignUpHandler signupCallback = new SignUpHandler() {
#Override
public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails)
{
Log.d("myCognito","sign up succeeded!");
// Sign-up was successful
// Check if this user (cognitoUser) needs to be confirmed
if(!userConfirmed)
{
Log.d("myCognito","not confirmed! Need to confirm");
confirmUser();
// This user must be confirmed and a confirmation code was sent to the user
// cognitoUserCodeDeliveryDetails will indicate where the confirmation code was sent
// Get the confirmation code from user
}
else {
Log.d("myCognito","confirmed!");
// The user has already been confirmed
}
}
#Override
public void onFailure(Exception exception)
{
Log.d("myCognito","sign up failed!");
// Sign-up failed, check exception for the cause
}
};
userPool.signUpInBackground("user1ID", password.getText().toString(), userAttributes, null, signupCallback);
}
private void confirmUser()
{
// Callback handler for confirmSignUp API
GenericHandler confirmationCallback = new GenericHandler() {
#Override
public void onSuccess() {
// User was successfully confirmed
Log.d("myCognito","Confirmed User Success!");
}
#Override
public void onFailure(Exception exception) {
// User confirmation failed. Check exception for the cause.
Log.d("myCognito","Confirmed User faileure :(");
}
};
}
}
Again im really confused on how to make this class, when i used mobile hub, the code was all over the place in the sample app.
Try this Document Amazon Cognito Credentials Provider
In Mobile hub look for this file CognitoUserPoolsSignInProvider
It has all the details how the sign in works
Below is the Authenctication Handler (I have commented few things to remove errors)
private AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(final CognitoUserSession userSession, final CognitoDevice newDevice) {
Log.i(LOG_TAG, "Logged in. " + userSession.getIdToken());
cognitoUserSession = userSession;
if (null != resultsHandler) {
ViewHelper.showDialog(activity, activity.getString(title_activity_sign_in),
activity.getString(login_success) + " " + userSession.getIdToken());
resultsHandler.onSuccess(CognitoUserPoolsSignInProvider.this);
}
initializedLatch.countDown();
}
#Override
public void getAuthenticationDetails(
final AuthenticationContinuation authenticationContinuation, final String userId) {
if (null != username && null != password) {
final AuthenticationDetails authenticationDetails = new AuthenticationDetails(
username,
password,
null);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
authenticationContinuation.continueTask();
}
initializedLatch.countDown();
}
#Override
public void getMFACode(final MultiFactorAuthenticationContinuation continuation) {
multiFactorAuthenticationContinuation = continuation;
//todo uncomment it
/* final Intent intent = new Intent(context, MFAActivity.class);
activity.startActivityForResult(intent, MFA_REQUEST_CODE);*/
}
#Override
public void authenticationChallenge(final ChallengeContinuation continuation) {
throw new UnsupportedOperationException("Not supported in this sample.");
}
#Override
public void onFailure(final Exception exception) {
Log.e(LOG_TAG, "Failed to login.", exception);
if (null != resultsHandler) {
ViewHelper.showDialog(activity, activity.getString(R.string.title_activity_sign_in),
"Failed" + " " + exception);
// activity.getString( //todo uncomment it) + " " + exception);
resultsHandler.onError(CognitoUserPoolsSignInProvider.this, exception);
}
initializedLatch.countDown();
}
};
This is the onClick Listener
#Override
public View.OnClickListener initializeSignInButton(final Activity signInActivity,
final View buttonView,
final IdentityManager.SignInResultsHandler resultsHandler) {
this.activity = signInActivity;
this.resultsHandler = resultsHandler;
// User Pools requires sign in with the username or verified channel.
// Mobile Hub does not set up email verification because it requires SES verification.
// Hence, prompt customers to login using the username or phone number.
final EditText emailField = (EditText) activity.findViewById(EDIT_TEXT_USERNAME_ID);
emailField.setHint(R.string.button_text_sign_in);
final View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
username = ViewHelper.getStringValue(activity, EDIT_TEXT_USERNAME_ID);
password = ViewHelper.getStringValue(activity, EDIT_TEXT_PASSWORD_ID);
final CognitoUser cognitoUser = cognitoUserPool.getUser(username);
cognitoUser.getSessionInBackground(authenticationHandler);
}
};
buttonView.setOnClickListener(listener);
return listener;
}

Lock Auth0 for android not returning UserProfile on authentication

I'm using Lock for providing Login functionality in my android App to users.
Here is my code:
private Lock lock;
private LocalBroadcastManager broadcastManager;
private BroadcastReceiver authenticationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String idToken = intent.getStringExtra("com.auth0.android.lock.extra.IdToken");
String tokenType = intent.getStringExtra("com.auth0.android.lock.extra.TokenType");
Log.i(TAG, "User logged in with " + idToken + " "+ tokenType);
}
};
//Not sure use of this callback though its not being called anytime.
private LockCallback callback = new AuthenticationCallback() {
#Override
public void onAuthentication(Credentials credentials) {
Log.d(TAG, "Authenticated");
}
#Override
public void onCanceled() {
Log.d(TAG, "Authentication cancelled");
}
#Override
public void onError(LockException error) {
Log.d(TAG, "Authentication Error");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Auth0 auth0 = new Auth0(getString(R.string.auth0_clientId), getString(R.string.auth0_domain));
this.lock = Lock.newBuilder(auth0, callback)
.build();
broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.registerReceiver(authenticationReceiver, new IntentFilter("com.auth0.android.lock.action.Authentication"));
startActivity(this.lock.newIntent(this));
}
I have following two questions:
1). First of all I don't understand why it needs callback though it doesn't callback even after authentication succeeded.
2). Shouldn't LocalBroadcastManager get response with UserProfile information instead of token information?
I'm using Lock version: com.auth0.android:lock:2.0.0-beta.2
Is there any better way to do it?
Thanks in advance!
have you tried onSuccess method? I cant see in your code, that's why it's not executing after successful attempt.
Override onSuccess method in your LockCallback callback, this will return UserProfile.
/**
* Callback for authentication API calls to Auth0 API.
*/
public interface AuthenticationCallback extends Callback {
/**
* Called when authentication is successful.
* It might include user's profile and token information.
* #param profile User's profile information or null.
* #param token User's token information (e.g. id_token).
*/
void onSuccess(UserProfile profile, Token token);
}
Source

Categories

Resources