Unable to get bundle data from two different activities - android

I'm able to get data from each single activity but unable to get when calling from both activities at a time.
I have 3 activities
1.GoogleLogin
2.FacebookLogin
3.MainActivity
I have this in my GoogleLogin:
#Override
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Intent i = new Intent(getApplicationContext(),MainActivity.class);
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("Google", "Logged in using Google Account");
bundle.putString("GoogleUsername", currentUser.getDisplayName());
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT;
}
I have this in my FacebookLogin:
if (session.isOpened()) {
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Intent i = new Intent(FBMainActivity.this,MainActivity.class);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("Facebook", "Logged in using Facebook Account");
bundle.putString("LastName", user.getLastName());
bundle.putString("FirstName", user.getFirstName());
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
}
}
}).executeAsync();
}
In My MainActivity I get them as shown:
// 1. get passed intent
Intent facebookintent = getIntent();
// 2. get message value from intent
String lastName = facebookintent.getStringExtra("LastName");
String firstName = facebookintent.getStringExtra("FirstName");
// 3. get bundle from intent
Bundle facebookbundle = facebookintent.getExtras();
// 4. get status value from bundle
String facebookstatus = facebookbundle.getString("Facebook");
// 1. get passed intent
Intent googleintent = getIntent();
// 2. get message value from intent
String userName = googleintent.getStringExtra("GoogleUsername");
// 3. get bundle from intent
Bundle googlebundle = facebookintent.getExtras();
// 4. get status value from bundle
String googlestatus = googlebundle.getString("Google");
if (facebookstatus=="Logged in using Facebook Account"){
// 3. show message on textView
((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + lastName + " " + firstName);
}else if (googlestatus=="Logged in using Google Account"){
// 3. show message on textView
((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + userName);
}
I'm unable to get GoogleUsername but able to get them individually when able to call from each single activity.

As per the logic flow, your activity can get started by either facebook or google login.
so you have to check and use it appropiately. do something like this
// 1. get passed intent
Intent intent = getIntent();
if (intent.getStringExtra("Facebook") != null){
// 2. get message value from intent
String lastName = intent.getStringExtra("LastName");
String firstName = intent.getStringExtra("FirstName");
if(intent.getStringExtra("Facebook").equals("Logged in using Facebook Account")){
((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + lastName + " " + firstName);
}
}else if(intent.getStringExtra("Google") != null){
// 2. get message value from intent
String userName = googleintent.getStringExtra("GoogleUsername");
// 3. get bundle from intent
Bundle googlebundle = facebookintent.getExtras();
if(intent.getStringExtra("Google").equals("Logged in using Google Account")){
((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + userName);
}
}

you need check before check googleStatus and facebookStatus. ( in java we dont compare two String with == , compare that with .equals() method )
you need check that in your bundle google account is exists or facebook account, for that you need following code:
if (bundle != null)
{
if ( bundle.containsKey("Facebook") )
{
// user logged in with facebook account
}
else if (bundle.containsKey("Google") )
{
// check google account
}
}

Related

How to get message from GCM message body in android?

I have an app in which server sends some push notification using GCM server, The implementation is done on both side but i am facing problem is that i can't get notification from message body, it is always showing me "null". But i can see message in messag body using debug.
String message = bundle.getString("message");
Log.e(TAG, "onMessageReceived::" + message);
Log.e(TAG, "from::" + from);
and message body is :-
Bundle[{google.sent_time=1497866966996, google.message_id=0:1497866967011288%466cbbd8466cbbd8, notification=Bundle[{priority=high, body=Your wallet has been credited with 1.000 point(s)., title=Wallet credited}], collapse_key=com.s.baty}]
Try ,
Bundle notificationData = bundle.getBundle("notification");
String body = notificationData.getString("body");
It received correct data only
String bodymessage = bundle.getString("body");
Problem is print message after converting Sting
Log.e(TAG, "onMessageReceived::" + message.toString());
You can receive message in onMessage() function of GCMIntentService implementing class. I have created a function for getting proper message and key.
#Override
protected void onMessage(Context context, Intent intent) {
dumpIntent(intent);
}
public void dumpIntent(Intent i) {
Bundle bundle = i.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
Log.e("Intent Data", "[" + key + "=" + bundle.get(key) + "]");
}
}
}
After that you will easily set message with NotificationManager.

AbstractAccountAuthenticator prompt login in refresh token when stored credential are no longer valid

I'm implementing the android account authenticator, so far I can add accounts get a token etc.
The problem is when I change credential server side.
As I can't get notified from the server if credentials changed, my next API request will be denied as the token is not longer valid.
After getting a request denied there could be 2 reasons for it -> token expired or credentials no longer valid
When this happen I invalidate the token saved and call getAuthToken()
In my getAuthToken() I first attempt a request for a new token, if it gets denied means that credential are not ok anymore so I need to prompt login activity.
The problem is AccountAuthenticatorResponse.onError seems only able to log the error and that's it.
I tried to use AccountAuthenticatorResponse.onResult passing the bundle with the KEY_INTENT for login activity but it does't do anything.
Any thoughts?
#Override
public Bundle getAuthToken(final AccountAuthenticatorResponse authenticatorResponse, final Account account,
final String authTokenType, Bundle bundle) throws NetworkErrorException {
//Get the account manager to access the account details
final AccountManager accountManager = AccountManager.get(mContext);
String authToken = accountManager.peekAuthToken(account, authTokenType);
//If auth token is null then try to log in the user with the stored credentials
//It could be that previous token has expired
if (authToken == null) {
final String password = accountManager.getPassword(account);
final String clientID = accountManager.getUserData(account, CLIENT_ID_KEY);
final String apiSecret = accountManager.getUserData(account, API_SECRET_KEY);
final String serverUrl = accountManager.getUserData(account, SERVER_ADDRESS_KEY);
if (password != null && clientID != null && apiSecret != null && serverUrl != null) {
Logger.log(LOG_TAG, "Requesting new token...", Log.VERBOSE);
ApiRequestManager.getInstance(mContext)
.getToken(serverUrl, clientID, apiSecret, account.name, password,
new NetworkCallBack() {
#Override
public void tokenReceived(Token JsonToken) {
//Credentials still valid, token received
//Returning data back to the account authenticator
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, JsonToken.getAccess_token());
authenticatorResponse.onResult(result);
}
#Override
public void errorReceivingToken(VolleyError errorResponse) {
//If we are here with error 400 it only means credentials have changed
//I should prompt LogIn activity at this point
if (errorResponse.networkResponse.statusCode == 400) {
Bundle loginActivityBundle =
promptLoginActivity(authenticatorResponse, account.type, authTokenType, null);
// authenticatorResponse.onResult(loginActivityBundle);
authenticatorResponse.onError(errorResponse.networkResponse.statusCode, "error");
}
}
});
return null;
}
}
//If we got an authToken return the account and login info in a bundle
if (authToken != null) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
//If we are here then means either we do not have an account signed
//or credentials are no longer valid -> prompt login procedure again
return promptLoginActivity(authenticatorResponse, account.type, authTokenType, null);
}
I found the solution.
When I invoke getAuthToken() i pass an accountManagerCallback which receives either success or fail, from here I can prompt logIn if it was a fail due to auth exception.

Push Notification Using FCM Android with deleting the token

I have to show push notification while user is logged in.So when app opens am taking deviceToken.So it will register to server always.But when user logout i dont want to show push notification.So how can i do it?
Now i have done with checking preference value like the below code,
public void onMessageReceived(String from, Bundle data) {
loginPref = getSharedPreferences("loginPreference", Context.MODE_PRIVATE);
mEditPrefs = loginPref.edit();
userID = loginPref.getString("userId", null);
if(userID!=null){
Bundle bundle = data.getBundle("notification");
Log.d("Bundle123::", bundle + "");
if (bundle != null) {
String text = bundle.getString("text");
String body = bundle.getString("body");
String title = bundle.getString("title");
Log.d("text123::", text + "");
Log.d("title123::", title + "");
Intent in = new Intent();
in.setAction("GCM_RECEIVED");
sendBroadcast(in);
sendNotification(title,body);
}
}
But when app backgrounds this condition doesn't work.How can i do it?Because i cant delete the token because when am trying login i have to send device token too..
While logout time tell to back end side to do device token as null.

AccountManager.blockingGetAuthToken() does not prompt for credentials

I use a SyncAdapter and an AccountAuthenticator in my app. When doing the sync stuff, I call AccountManager.blockingGetAuthToken to get an access token. I understand this method that way, that it starts my Log-in activity when it can not get a token (or in other words, when the getAuthToken methods returns an Intent to start the Activity).
But it just returns null, without launching the Activity.
This is the getAuthToken method from my authenticator.
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
// Extract the username and password from the Account Manager, and ask
// the server for an appropriate AuthToken.
final AccountManager am = AccountManager.get(mContext);
String authToken = am.peekAuthToken(account, authTokenType);
// Lets give another try to authenticate the user
if (TextUtils.isEmpty(authToken)) {
final String password = am.getPassword(account);
if (password != null) {
try {
authToken = APIHelper.getInstance().logIn(account.name, password);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// If we get an authToken - we return it
if (!TextUtils.isEmpty(authToken)) {
// cache
am.setAuthToken(account, authTokenType, authToken);
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
// If we get here, then we couldn't access the user's password - so we
// need to re-prompt them for their credentials. We do that by creating
// an intent to display our AuthenticatorActivity.
final Intent intent = new Intent(mContext, AuthActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
intent.putExtra(AuthActivity.ARG_ACCOUNT_TYPE, account.type);
intent.putExtra(AuthActivity.ARG_AUTH_TYPE, authTokenType);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
By the way, most of the code is from
this blog.
It seems the asker figured it out. For posterity, it works if you use this instead:
AccountManagerFuture<Bundle> resultFuture = accountManager.getAuthToken(
account,
AUTH_TOKEN_TYPE,
null,
activity,
null,
null
);
Bundle bundle = resultFuture.getResult();
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
I guess blockingGetAuthToken() is unable to do this automatically because it lacks the activity parameter. And the documentation is incorrect.

Authenticating to OAuth2 Services lesson(trouble)

I am trying to follow the lesson on developer.android.com and I am getting stuck on the
am.getAuthToken(
myAccount_, AUTH_TOKEN_TYPE,options,this,new OnTokenAcquired(),new Handler(new OnError()));
I don't get what to put in for the myAccount_; Is it accounts that is linked to the account array? Account[] accounts = accountManager.getAccountsByType("com.google");
The token part on class OnTokenAcquired is also gennerating an error saying it isn't a var, should I just make it a global var even though it is suposse to be a constant in the AccountManager.KEY_AUTHTOKEN?
This is the other link for the Authentication lesson and I am getting an error with DIALOG_ACCOUNTS, showDialog(DIALOG_ACCOUNTS) and manager.getAuthToken(account, AUTH_TOKEN_TYPE, null, activity, new AccountManagerCallback<Bundle>() in that tutorioul. I haven't gone much further in it because of the errors I am currently getting.
I don't get why these errors are happening? I assume it is just me not putting in the right vars though.
Any suggestions?
Here is the code I have copied.
public class AccountManagerActivity extends Activity {
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
String AUTH_TOKEN_TYPE = "Manage your tasks";
String your_api_key;
String your_client_id;
String your_client_secret;
String token;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
URL url = new URL("https://www.googleapis.com/tasks/v1/users/#me/lists?key=" + your_api_key);
URLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("client_id", your_client_id);
conn.addRequestProperty("client_secret", your_client_secret);
conn.setRequestProperty("Authorization", "OAuth " + token);
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.invalidateAuthToken(token, AUTH_TOKEN_TYPE);
am.getAuthToken(
/*Error here*/ myAccount_, // Account retrieved using getAccountsByType()
AUTH_TOKEN_TYPE, // Auth scope
options, // Authenticator-specific options
this, // Your activity
new OnTokenAcquired(), // Callback called when a token is successfully acquired
new Handler(new OnError())); // Callback called if an error occurs
}
}
And then the OnTokenAcquired class
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
// TODO Auto-generated method stub
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle = result.getResult();
// The token is a named value in the bundle. The name of the value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
/*Error here*/ Token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Intent launch = (Intent) result./*Error here*/get(AccountManager.KEY_INTENT);
if (launch != null) {
/*Error here*/ startActivityForResult(launch, 0);
return;
}
}
}
am.invalidateAuthToken(token, AUTH_TOKEN_TYPE);
should be
am.invalidateAuthToken(AUTH_TOKEN_TYPE, token);

Categories

Resources