AccountManagerCallback is not working with kitkat - android

I am using android account manager to authenticate twitter account.It is working fine for jellybean but for kitkat accountmanager callback is not coming.Here is my sample code
accountManager.getAuthToken(twitterAccount, Constants.TWITTER_TOKEN,
null, (Activity) mContext, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> amf) {
try {
Bundle b = amf.getResult();
OAUTH_TOKEN = b
.getString(AccountManager.KEY_AUTHTOKEN);
if (OAUTH_SECRET != null && OAUTH_TOKEN != null) {
authenticate();
}
} catch (Exception e) {
Toast.makeText(mContext,"Error while getting token",Toast.LENGTH_SHORT).show();
}
}
}, null);
Note:Constants.TWITTER_TOKEN = "com.twitter.android.oauth.token";

Related

CompanionDeviceManager associate method not calling callback methods

I am trying to use CompanionDeviceManager class to pair our BLE device with our Android (Version 10) phone without need of location permission. Here I am using below code:
private void initialiseCompanionDeviceManager() {
if (equalOrGreaterThanOreo()) {
companionDeviceManager = getSystemService(CompanionDeviceManager.class);
deviceFilter = new BluetoothLeDeviceFilter.Builder()/*.setNamePattern(Pattern.compile("fret zealot"))*/.build();
pairingRequest = new AssociationRequest.Builder()
.addDeviceFilter(deviceFilter)
//.setSingleDevice(true)
.build();
associateDevice();
}
}
private void associateDevice() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
companionDeviceManager.associate(pairingRequest, new CompanionDeviceManager.Callback() {
#Override
public void onDeviceFound(IntentSender chooserLauncher) {
try {
Log.e("BLEDevice", "Device found");
startIntentSenderForResult(chooserLauncher,
SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
Log.e("BLEDevice", "EXception");
}
}
#Override
public void onFailure(CharSequence error) {
Log.e("BLEDevice", "Device error: "+error);
}
}, null);
}
}
But it is not giving any callback in both methods. nothing happens. if anyone have idea about that, please bring me out of this.

How can I make other apps play/pause music?

I'm making a media controller app similar to this example made by google. https://github.com/googlesamples/android-media-controller
However, I want to make a function that can resume playing music or pause given package name. I managed to return a list of package names.
PS. I'm using react native that's why I need a fucntion that I can call from the react side.
public void getMediaApps (Callback callback) {
// = getPackageManager();
ArrayList<MediaAppDetails> mediaApps = new ArrayList<MediaAppDetails>();
Intent mediaBrowserIntent = new Intent(MediaBrowserServiceCompat.SERVICE_INTERFACE);
List<ResolveInfo> services = packageManager.queryIntentServices(
mediaBrowserIntent,
PackageManager.GET_RESOLVED_FILTER
);
if (services != null && !services.isEmpty()) {
for (ResolveInfo info : services) {
mediaApps.add(
new MediaAppDetails(info.serviceInfo, packageManager, resources)
);
}
}
WritableArray waPackagenames = Arguments.createArray();
// ArrayList<String> packagenames = ArrayList<String>()
if(mediaApps != null && !mediaApps.isEmpty()){
for(MediaAppDetails mediaApp : mediaApps){
waPackagenames.pushString(mediaApp.packageName);
}
}
callback.invoke(waPackagenames);
}
I've been trying to do this for 3 days now, but no luck.
Probably won't make such of a difference but this is where I got so far with the play function.
#ReactMethod
public void play (String packageName) {
PackageManager pm = this.packageManager;
Resources res = this.resources;
ServiceInfo serviceInfo = MediaAppDetails.findServiceInfo(packageName, pm);
mMediaAppDetails = new MediaAppDetails(serviceInfo, pm, res);
MediaSessionCompat.Token token = mMediaAppDetails.sessionToken;
if (token == null) {
if (mMediaAppDetails.componentName != null) {
mBrowser = new MediaBrowserCompat(this.reactContext, mMediaAppDetails.componentName,
new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
setupMediaController();
// mBrowseMediaItemsAdapter.setRoot(mBrowser.getRoot());
}
#Override
public void onConnectionSuspended() {
//TODO(rasekh): shut down browser.
// mBrowseMediaItemsAdapter.setRoot(null);
}
#Override
public void onConnectionFailed() {
showToastAndFinish("connection failed .. shit!");
}
}, null);
mBrowser.connect();
} else if (mMediaAppDetails.sessionToken != null) {
setupMediaController();
}
token = mBrowser.getSessionToken();
Toast.makeText(this.reactContext, "no token can't open controller", Toast.LENGTH_SHORT).show();
// toast
}
// Toast.makeText(this.reactContext, "found token", Toast.LENGTH_SHORT).show();
if(mBrowser == null )mBrowser = new MediaBrowserCompat(this.reactContext, new ComponentName(packageName, "MainActivity"), null, null);
MediaControllerCompat.TransportControls transportControls;
try{
mController = new MediaControllerCompat(this.reactContext, token);
if(mController!= null) {
transportControls = mController.getTransportControls();
transportControls.play();
}
}catch(Exception E){
Log.w("Error",E);
Log.w("Error","couldn't create mediaControllerCompat");
// System.out.println(E);
// System.out.println("couldn't create mediaControllerCompat");
}
}

NFC tag(for NfcA) scan works only from the second time

I wrote a custom plugin to read blocks of data from an NfcA(i.e.non-ndef) tag. It seems to work fine , but only after the second scan. I am using Activity intent to derive the "NfcAdapter.EXTRA_TAG" to later use it for reading the values. I am also updating the Intents in onNewIntent(). OnNewIntent gets called after the second scan and after that I get result all the time.But in the first scan onNewIntent does not gets called, hence I end up using the Activity tag that does not have "NfcAdapter.EXTRA_TAG", hence I get null. Please see the my code below.
SE_NfcA.java(my native code for plugin)
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
String Result = "";
String TypeOfTalking = "";
if (action.contains("TalkToNFC"))
{
JSONObject arg_object = args.getJSONObject(0);
TypeOfTalking = arg_object.getString("type");
if(TypeOfTalking != "")
{
if (TypeOfTalking.contains("readBlock"))
{
if(TypeOfTalking.contains("#"))
{
try
{
String[] parts = TypeOfTalking.split("#");
int index = Integer.parseInt(parts[1]);
Result = Readblock(cordova.getActivity().getIntent(),(byte)index);
callbackContext.success(Result);
}
catch(Exception e)
{
callbackContext.error("Exception Reading "+ TypeOfTalking + "due to "+ e.toString());
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
#Override
public void onNewIntent(Intent intent) {
ShowAlert("onNewIntent called");
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
super.onNewIntent(intent);
getActivity().setIntent(intent);
savedTag = tagFromIntent;
savedIntent = intent;
}
#Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getActivity().getIntent());
super.onPause(multitasking);
if (multitasking) {
// nfc can't run in background
stopNfc();
}
}
#Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getActivity().getIntent());
super.onResume(multitasking);
startNfc();
}
public String Readblock(Intent Intent,byte block) throws IOException{
byte[] response = new byte[]{};
if(Intent != null)
{
Tag myTag = Intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if(savedTag != null)
myTag = savedTag;
if(myTag != null)
{
try{
Reader nTagReader = new Reader(myTag);
nTagReader.close();
nTagReader.connect();
nTagReader.SectorSelect(Sector.Sector0);
response = nTagReader.fast_read(block, block);
nTagReader.close();
return ConvertH(response);
}catch(Exception e){
ShowAlert(e.toString());
}
}
else
ShowAlert("myTag is null.");
}
return null;
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && !getActivity().isFinishing()) {
try {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
} catch (IllegalStateException e) {
// issue 110 - user exits app with home button while nfc is initializing
Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(getActivity());
} catch (IllegalStateException e) {
// issue 125 - user exits app with back button while nfc
Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
}
}
}
});
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
}
My index.js file
nfc.addTagDiscoveredListener(
function(nfcEvent){
console.log(nfcEvent.tag.id);
alert(nfcEvent.tag.id);
window.echo("readBlock#88");//call to plugin
},
function() {
alert("Listening for NFC tags.");
},
function() {
alert("NFC activation failed.");
}
);
SE_NfcA.js(plugin interface for interaction b/w index.js and SE_NfcA.java)
window.echo = function(natureOfTalk)
{
alert("Inside JS Interface, arg =" + natureOfTalk);
cordova.exec(function(result){alert("Result is : "+result);},
function(error){alert("Some Error happened : "+ error);},
"SE_NfcA","TalkToNFC",[{"type": natureOfTalk}]);
};
I guess I have messed up with the Intents/Activity Life-Cycle, please help. TIA!
I found a tweak/hack and made it to work.
Before making any call to read or write, I made one dummy Initialize call.
window.echo("Initialize");
window.echo("readBlock#88");//call to plugin to read.
And in the native code of the plugin, on receiving the "Initialize" token I made a startNFC() call.
else if(TypeOfTalking.equalsIgnoreCase("Initialize"))
{
startNfc();
}

Android Google Play Services returns invalid token for blogger api

I've been given access to the blogger API, I've confirmed that on my developer console.
I've also written some code to perform oAuth2 with Google Play Services using some of the code below.
String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
GoogleAuthUtil.getToken(context, "myEmail#gmail.com", mScope);
It returns a token. As it should.
However, once I try to access the api using the token i get a error.
Unexpected response code 403 for https://www.googleapis.com/blogger/v3/users/self/blogs
Here is my request:
And here is my response:
Here is my BaseActivity.java code that gets the token:
public class BaseActivity extends Activity {
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
private static final String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
private String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
public ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialog = new ProgressDialog(this);
login();
}
public void login() {
pickUserAccount();
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getToken();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, "Pick Account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
// Receiving a result that follows a GoogleAuthException, try auth again
getToken();
}
}
private void getToken() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new getTokenTask(BaseActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "Not online", Toast.LENGTH_LONG).show();
}
}
}
/**
* This method is a hook for background threads and async tasks that need to
* provide the user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
// Because this call comes from the AsyncTask, we must ensure that the following
// code instead executes on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, BaseActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
public boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
public class getTokenTask extends AsyncTask{
Activity mActivity;
String mScope;
String mEmail;
getTokenTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
#Override
protected Object doInBackground(Object[] params) {
try {
String token = fetchToken();
Preferences.saveString(Constants.KEY_BLOGGER_TOKEN, token);
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
((BaseActivity)mActivity).handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
}
return null;
}
}
}
I've been banging my head against the wall on this one. Anyone have any ideas?
Finally figured it out.
My build.gradle file somehow ended up having a different Application ID than my manifest. I changed it so they both match the manifest, and boom! it worked.

How to share the status for FB in Android programatically

I want to share the text/image programatically from my app on facebook.How should I proceed for that.After lots of googling I found lots of sample apps but as the latest FB SDK is deprecated those APIs it is hard to find the way using new SDK.Please help me out for this issue.
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x- howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getApplicationContext(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
This is what i get for fb API 3.5 doc & which I have tried but it is crashing the app by saying session is null.
Here your session is null because you have not started it yet.
You have to start your session after login.
You can achieve this by using
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
});
For more information try going through the tutorials from http://developers.facebook.com/docs/android/scrumptious/authenticate/. These are really helpful.
Here is how I implemented --
This class is used to do initial stuffs to facebook
LoginFacebookClass
/**
* for integrating facebook in your app..
* Firstly import FacebookSDK lib project and add in your project as lib project.
* then
* create an instance of this class
* and, then call the facebook login method by passing reference of your activity and true, if you want to fetch data and, false if you want to share data on faceboko
* Please do whatever you want in the interface callback methods
* implemented by this class
*
*
* Note: Please write a line exactly in your activity's on activity result as
* -- Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
* here, 'Session' is Class of Facebook.
* 'this' is reference of your activity
*/
public class FacebookLoginClass implements FB_Callback
{
Context context;
FBImPlmentation fbImpl;
String mImageURLString = "", mPhotoTypeString = "";
// private FBBean userDataBean;
/**
* constructor for FacebookLoginClass
* #param con : context of activity
* #param string
* #param mImageURLString2
*/
public FacebookLoginClass(Context con)
{
this.context = con;
fbImpl = FBImPlmentation.getInstance(context, this);
}
public FacebookLoginClass(Context con, String imageURLString, String photoType)
{
this.context = con;
fbImpl = FBImPlmentation.getInstance(context, this);
mImageURLString = imageURLString;
mPhotoTypeString = photoType;
}
/**
* method for initiating facebook Login
* #param isDataFetch : true for fetching user data, false for sharing on wall
*/
public void facebookLogin(boolean isDataFetch)
{
fbImpl.CheckSession(isDataFetch);
}
/**
* method for facebookLogout
*/
public void facebookLogout()
{
fbImpl.fbLogout();
}
#Override
public void onLogin(Session s)
{
fbImpl.getDataFromFB(s);
}
#Override
public void onLoginForShareData()
{
Log.e("facebook.", "True in..........");
Bundle postParams = new Bundle();
postParams.putString("name", "");
postParams.putString("caption", "");
postParams.putString("description", " Android, share your pics and videos");
if (mPhotoTypeString.equalsIgnoreCase("photo"))
{
postParams.putString("picture", mImageURLString);
}
else
{
postParams.putString("link", "");
}
fbImpl.publishFeedDialog(postParams);
}
#Override
public void onAuthFailiure()
{
}
#Override
public void onUserData(FBBean fbUserDataBean)
{
try
{
if (BejoelUtility.isNetworkAvailable(context))
{
String imageURLString = "http://graph.facebook.com/" + fbUserDataBean.getUserID() + "/picture?type=large";
new FacebookTwitterLoginAsyncTask(context, fbUserDataBean.getFirstNAme(), fbUserDataBean.getLastName(),
fbUserDataBean.getMailId(), fbUserDataBean.getUserBday(), fbUserDataBean.getUserSex(), "", "", imageURLString,
fbUserDataBean.getAccessToken(), "facebook").execute();
}
else
{
BejoelUtility.showMsgDialog(context, context.getString(R.string.app_name), context.getString(R.string.no_internet));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onPost(boolean postStatus)
{
// TODO Auto-generated method stub
}
#Override
public void onFriendRequest(boolean shareAppStatus)
{
// TODO Auto-generated method stub
}
#Override
public void onLogout(boolean status)
{
// TODO Auto-generated method stub
}
}
This class interact with facebook
public class FBImPlmentation
{
public static List<String> READ_PERMISSIONS = Arrays.asList("email");
public List<String> WRITE_PERMISSIONS = Arrays.asList("publish_actions");
private static FBImPlmentation fbImpl;
private FB_Callback mInterface;
private static Activity activity;
boolean isDataFetch=false;
private String mAccessTokenString = "";
/**
* constructor for facebookImplementation
* #param con :context of activity via FacebookLogin Class
* #param mInterface : refrence of class implementing FB_Callback interface..as in our case,
* it is refrence of FacebookLogin Class
* #return : instance of FBImplementation
*/
public static FBImPlmentation getInstance(Context con, FB_Callback mInterface)
{
activity = (Activity) con;
if (fbImpl == null)
fbImpl = new FBImPlmentation();
fbImpl.mInterface = mInterface;
return fbImpl;
}
/**
* method to be called for facebook Logout
*/
public void fbLogout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
mInterface.onLogout(true);
}
/**
* method for checking session.
* if session is not open, then open a new session.
* If session is already open then..just call the fbcallback onlogin method
* #param isDataFetch2
*/
public void CheckSession(boolean isDataFetch2)
{
fbImpl.isDataFetch= isDataFetch2;
Session s = Session.getActiveSession();
if (s != null && s.isOpened())
{
if(isDataFetch)
mInterface.onLogin(s);
else
mInterface.onLoginForShareData();
mAccessTokenString = s.getAccessToken();
}
else
{
Session.openActiveSession(activity, true, mFBCallback);
}
}
// Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, permissions);
Session.StatusCallback mFBCallback = new Session.StatusCallback()
{
// call method is always called on session state change
#Override
public void call(Session session, SessionState state, Exception exception)
{
if (session.isOpened())
{
List<String> permissions = session.getPermissions();
if (!isSubsetOf(READ_PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, READ_PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
else if(isDataFetch)
{
mInterface.onLogin(session);
}
else
{
mInterface.onLoginForShareData();
}
}
}
};
/**
* method for fetching the user data
* #param session : it takes the refrence of active session
*/
public void getDataFromFB(Session session)
{
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
// code to retrieve user's data and pass to signup fragment
FBBean fbUserDataBean = new FBBean();
if (mAccessTokenString != null)
fbUserDataBean.setAccessToken(mAccessTokenString);
else
{
fbUserDataBean.setAccessToken("");
}
if (user.getUsername() != null && !(user.getUsername().equals(null)))
fbUserDataBean.setUserName(user.getUsername());
else
{
fbUserDataBean.setUserName("");
}
if (user.getFirstName() != null && !(user.getFirstName().equals(null)))
fbUserDataBean.setFirstNAme(user.getFirstName());
else
{
fbUserDataBean.setFirstNAme("");
}
if (user.getLastName() != null && !(user.getLastName().equals(null)))
fbUserDataBean.setLastName(user.getLastName());
else
{
fbUserDataBean.setLastName("");
}
if (user.getBirthday() != null && !(user.getBirthday().equals(null)))
fbUserDataBean.setUserBday(user.getBirthday());
else
{
fbUserDataBean.setUserBday("");
}
if (user.asMap().get("gender") != null)
{
fbUserDataBean.setUserSex(user.asMap().get("gender").toString());
}
else
{
fbUserDataBean.setUserSex("");
}
if (user.getProperty("email") != null && !(user.getProperty("email").equals(null)))
fbUserDataBean.setMailId(user.getProperty("email").toString());
else
{
fbUserDataBean.setMailId("");
}
if (user.getId() != null && !(user.getId().equals(null)))
fbUserDataBean.setUserID(user.getId());
else
{
fbUserDataBean.setUserID("");
}
// String[] sportsArray = FacebookUtils.getSportsArray(user.getInnerJSONObject());
// if (sportsArray != null && !(sportsArray.equals(null)))
// fbUserDataBean.setSportsname(sportsArray);
mInterface.onUserData(fbUserDataBean);
}
}
});
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
{
for (String string : subset)
{
if (!superset.contains(string))
{
return false;
}
}
return true;
}
/**
* method for publishing posts
*/
public void publishFeedDialog(Bundle postParams)
{
Session s = Session.getActiveSession();
List<String> permissions = s.getPermissions();
if (!isSubsetOf(WRITE_PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity,
WRITE_PERMISSIONS);
s.requestNewPublishPermissions(newPermissionsRequest);
return;
}
// Bundle postParams = new Bundle();
// postParams.putString("name", "Facebook SDK for Android");
// postParams.putString("caption", "Build great social apps and get more installs.");
// postParams.putString("description", "Video by Lata manadjahgkfdjhaskjd akhgfkjashfkjash");
// postParams.putString("link", "");
// postParams.putString("picture", "");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, Session.getActiveSession(), postParams))
.setOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(Bundle values, FacebookException error)
{
if (error == null)
{
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null)
{
mInterface.onPost(true);
}
else
{
// User clicked the Cancel button
mInterface.onPost(false);
}
}
else
if (error instanceof FacebookOperationCanceledException)
{
// User clicked the "x" button
// Toast.makeText(MainActivity.this.getApplicationContext(), "Publish cancelled",
// Toast.LENGTH_SHORT).show();
mInterface.onPost(false);
}
else
{
// Generic, ex: network error
// Toast.makeText(MainActivity.this.getApplicationContext(), "Error posting story",
// Toast.LENGTH_SHORT).show();
mInterface.onAuthFailiure();
}
}
}).build();
feedDialog.show();
}
}

Categories

Resources