Permission decline facebook sdk for android - android

Working on Facebook for android application. Unable to get publish permission.
When i request for permission it get added to decline permissions. Any suggestions.
public class MainActivity extends Activity implements OnClickListener {
private static final String PERMISSION_PUBLISH = "publish_actions";
private TextView textView;
private Button check;
private Button ask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView1);
check = (Button) findViewById(R.id.check_per);
ask = (Button) findViewById(R.id.get_per);
check.setOnClickListener(this);
ask.setOnClickListener(this);
findViewById(R.id.post).setOnClickListener(this);
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
session.refreshPermissions();
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
updateUi(user);
}
}).executeAsync();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Session session = Session.getActiveSession();
if (session != null) {
session.onActivityResult(MainActivity.this, requestCode, resultCode, data);
session.refreshPermissions();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
public void updateUi(GraphUser graphUser) {
textView.setText(graphUser.getFirstName());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.check_per:
checkForPermission();
break;
case R.id.get_per:
getPermission();
break;
case R.id.post:
post();
break;
default:
break;
}
}
private void checkForPermission() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// --- Shows PEMISSION_PUBLISH in declined permission not in
// permission granted
List<String> permissions = session.getDeclinedPermissions();
showToast("size : " + permissions.size());
for (int i = 0; i < session.getDeclinedPermissions().size(); i++) {
showToast("Has permission : " + permissions.get(i));
}
}
}
private void getPermission() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(MainActivity.this, PERMISSION_PUBLISH);
session.requestNewPublishPermissions(newPermissionsRequest);
}
}
private void post() {
Request.newStatusUpdateRequest(Session.getActiveSession(), "Status Update", new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response != null)
showToast(response.toString());
}
}).executeAsync();
}
}

You should go to app settings on developers.facebook.com to Status&Review tab and send request for Facebook review team, see https://developers.facebook.com/docs/apps/review/ for details.

Related

Unable show poup login when I login facebook second times in android

Here is my code for login in facebook:
private boolean isFirstTime;
private CustomProgressDialog customProgressDialog;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private String fbEmail;
private String fbName;
private String fbToken;
private String id;
private String avatar;
private LoginView mView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
isFirstTime = true;
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
}
Session.getActiveSession().addCallback(statusCallback);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(
Arrays.asList("email", "user_likes", "user_status")));
}
mView = new LoginView(this);
mView.imgLoginFaceBook.setOnClickListener(this);
mView.rllLoginSkip.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == mView.imgLoginFaceBook) {
facebookLogin();
}
if (v == mView.rllLoginSkip) {
ReplaceToPage.ReplaceToHome(this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
private void facebookLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email"));
request.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
session.openForRead(request.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
Session session = Session.getActiveSession();
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
private void updateFacebookView() {
final Session session = Session.getActiveSession();
if (isFirstTime) {
isFirstTime = false;
return;
}
if (session.isOpened()) {
Log.d("access token", session.getAccessToken());
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) {
if (user.asMap().toString().contains("email")) {
fbEmail = user.asMap().get("email").toString();
fbToken = user.asMap().get("id").toString();
Globals.FBToken = fbToken;
fbName = user.asMap().get("last_name").toString();
Globals.name = user.getName();
id = user.getId();
String idd = user.getId();
avatar = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.i("avatar", avatar);
ACCUtils.setStringPreferences(getApplicationContext(), "", avatar);
ReplaceToPage.ReplaceToHome(LoginActivity.this);
} else {
session.closeAndClearTokenInformation();
return;
}
}
}
});
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateFacebookView();
}
}
Here is my code for logout:
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
ACCUtils.setStringPreferences(getApplicationContext(), "", "");
Globals.FBToken = "";
The first login was woking good, but when I logout and login again, it doesn't show popup and allow app login from fb. I want to show popup, help me!!!!

facebook checkin permission error

In my application I am trying to checkin with specific location.
But everytime I have this error
{Response: responseCode: 403, graphObject: null, error: {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) Requires extended permission: publish_actions}, isFromCache:false}
I am do sure that I put publish_actions permission in my permission list.
What I did wrong here? and why I have such of error everytime?
Here is my code:
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()){
checkIn(session);
PrefsCacheManager.getInstance().putInCashe("accessToken" , session.getAccessToken());
}
}
}
private UiLifecycleHelper uiHelper;
private LocationManager locationManager;
private Location lastKnownLocation;
private UiLifecycleHelper lifecycleHelper;
private Location pickPlaceForLocationWhenSessionOpened = null;
private static final int PLACE_ACTIVITY = 1;
private String mPlaceId;
private static final Location LOCATION = new Location("") {{}};
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
lifecycleHelper = new UiLifecycleHelper(this, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChanged(session, state, exception);
}
});
lifecycleHelper.onCreate(savedInstanceState);
ensureOpenSession();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
init();
}
#Override
public void onStart() {
super.onStart();
mTracker.activityStart(this);
}
#Override
public void onStop() {
super.onStop();
mTracker.activityStop(this);
}
private boolean ensureOpenSession() {
if (Session.getActiveSession() == null ||
!Session.getActiveSession().isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChanged(session, state, exception);
}
});
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Toast.makeText(FacebookCheckIn.this, getString(R.string.fb_share_failed), Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
}
});
lifecycleHelper.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_ACTIVITY && resultCode == Activity.RESULT_OK){
displaySelectedPlace(resultCode);
} else if (requestCode == PLACE_ACTIVITY && resultCode == Activity.RESULT_CANCELED){
finish();
}
}
private void displaySelectedPlace(int resultCode) {
String results = "";
SmartBonusApplication application = (SmartBonusApplication) getApplication();
GraphPlace selection = application.getSelectedPlace();
if (selection != null) {
GraphLocation location = selection.getLocation();
mPlaceId = selection.getId();
checkFacebookSession();
}
}
private void setLocation() {
try {
LOCATION.setLatitude(mBrench.getLat());
LOCATION.setLongitude(mBrench.getLng());
startPickPlaceActivity(LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onError(Exception exception) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error").setMessage(exception.getMessage()).setPositiveButton("OK", null);
builder.show();
}
private void checkFacebookSession() {
final String[] PERMISSION_ARRAY_READ = {"publish_actions" , "user_checkins"};
final List<String> permissionList = Arrays.asList(PERMISSION_ARRAY_READ);
new Session.NewPermissionsRequest(FacebookCheckIn.this, permissionList);
Session session = Session.getActiveSession();
if (session != null){
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}else {
Session.openActiveSession(this, true, statusCallback);
}
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
private void checkIn(final Session pSession) {
Bundle params = new Bundle();
if (pSession.getAccessToken() != null) {
params.putString("place", String.valueOf(mPlaceId));
params.putString("message", mBrench.getCompany() + " " + mBrench.getAddress());
params.putString("coordinates", "{\"longitude\":" + mBrench.getLng() + ",\"latitude\":" + mBrench.getLat() + "}");
Request.Callback callback6 = new Request.Callback() {
public void onCompleted(Response response) {
checkInSuccess();
}
};
Request request6 = new Request(pSession, "me/checkins", params, HttpMethod.POST, callback6);
RequestAsyncTask task6 = new RequestAsyncTask(request6);
task6.execute();
}
}
private void checkInSuccess() {
Intent intent = new Intent(FacebookCheckIn.this, CheckinSuccessActivity.class);
intent.putExtra("branche", mBrench);
intent.putExtra("type", VKONTAKTE);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(0, 0);
}
private void init() {
mTracker = EasyTracker.getInstance(this);
mBrench = getIntent().getParcelableExtra("branche");
setLocation();
}
private void onSessionStateChanged(Session session, SessionState state, Exception exception) {
if (pickPlaceForLocationWhenSessionOpened != null && state.isOpened()) {
Location location = pickPlaceForLocationWhenSessionOpened;
pickPlaceForLocationWhenSessionOpened = null;
startPickPlaceActivity(location);
}
}
private void startPickPlaceActivity(Location location) {
if (ensureOpenSession()) {
SmartBonusApplication application = (SmartBonusApplication) getApplication();
application.setSelectedPlace(null);
Intent intent = new Intent(this, PickPlaceActivity.class);
PickPlaceActivity.populateParameters(intent, location, null);
startActivityForResult(intent, PLACE_ACTIVITY);
} else {
pickPlaceForLocationWhenSessionOpened = location;
}
}
}
You must have added the permission later. and since the session has already been created it's not asking for the publish_action permission.
So, destroy the session by logging-out of the facebook and then login again; or remove the application from your settings and then try. This way, it will ask for the publishing permission and you'll be able to publish successfully!
Edit:
Publishing with /checkins is now deprecated. Check - /{user-id}/checkins
You have to use the Open Graph now to publish stories with location.
You have to use
POST /{user_id}/feed
as described here: https://developers.facebook.com/docs/graph-api/reference/post#publishing
There you can add the place_id as parameter.

How to get the user info. using the android facebook sdk?

if (state.isOpened()) {
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Display the parsed user info
}
}
});
}
I have tried follow the facebook doc to get the user info when at the onSessionStateChange function, the problem is , it is weird that I follow the offical doc and it shows
Request.executeMeRequestAsync is depreciate , so I wonder how to implement get the user info in latest facebook sdk 3.6 ? What I would like to do is get the user info if the user logined. Thanks a lot
Update:
Anyway I would also like to ask whether this way to implement login is correct? There are two place in my app need to login
The first one is inside a fragment
public class Home extends Fragment {
public View rootView;
public ImageView HomeBg;
public ImageView buttonLoginLogout;
public TextView chi;
public TextView eng;
public ColorStateList oldColor;
public SharedPreferences prefs;
public EasyTracker tracker = null;
//Facebook login
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tracker = EasyTracker.getInstance(getActivity());
getActivity().getActionBar().hide();
rootView = inflater.inflate(R.layout.home, container, false);
buttonLoginLogout = (ImageView) rootView.findViewById(R.id.home_connectFB);
eng = (TextView) rootView.findViewById(R.id.btn_eng);
chi = (TextView) rootView.findViewById(R.id.btn_chi);
if (Utility.getLocale(getActivity()).equals("TC")) {
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = eng.getTextColors();
} else {
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = chi.getTextColors();
}
eng.setOnClickListener(setChangeLangListener("EN"));
chi.setOnClickListener(setChangeLangListener("TC"));
//Facebook login
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(getActivity());
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}
updateView();
return rootView;
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
tracker.set(Fields.SCREEN_NAME, "Landing Page " + Utility.getLocale(getActivity()));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
EasyTracker.getInstance(getActivity()).activityStop(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_take_a_selfie);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((LandingPage)getActivity()).tabHost.setCurrentTab(2);
}
});
} else {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_connect_facebook);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { onClickLogin(); }
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(getActivity(), this, true, statusCallback);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
public OnClickListener setChangeLangListener(final String lang) {
OnClickListener changeLangListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
Configuration config = new Configuration(getResources().getConfiguration());
if (Utility.getLocale(getActivity()).equals("TC") && lang.equals("EN")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchEN", null).build());
config.locale = Locale.ENGLISH;
chi.setTextColor(oldColor);
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
} else if (Utility.getLocale(getActivity()).equals("EN") && lang.equals("TC")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchTC", null).build());
config.locale = Locale.TRADITIONAL_CHINESE;
eng.setTextColor(oldColor);
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
}
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
onConfigurationChanged(config);
}
};
return changeLangListener;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().finish();
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(getActivity(),getResources().getString(R.string.app_id));
}
}
The other one is inside another activity
public class SharePicForm extends Activity {
private final String TAG = "SharePicForm";
public ImageView photoArea;
public ImageView sharePhotoBtn;
public EditText shareContent;
public Bitmap mBitmap;
public Context ctx;
public String shareTxt;
public String fileUri;
public static boolean isShowForm = true;
public ProgressDialog pd;
public EasyTracker tracker = null;
//Facebook share
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction {
NONE, POST_PHOTO
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = EasyTracker.getInstance(this);
setContentView(R.layout.share_pic_form);
ctx = this;
Utility.setHeader(this,R.string.selfie_header,false);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, callback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
}
}
photoArea = (ImageView) findViewById(R.id.photo_area);
shareContent = (EditText) findViewById(R.id.share_content);
if (getIntent() != null) {
Intent intent = getIntent();
fileUri = (String) intent.getStringExtra("photo");
} else if (savedInstanceState != null){
mBitmap = (Bitmap) savedInstanceState.getParcelable("bitmap") == null ? null : (Bitmap) savedInstanceState.getParcelable("bitmap");
}
FileInputStream inputStream;
try {
File imgSelected = new File(fileUri);
if (imgSelected.exists()) {
inputStream = new FileInputStream(imgSelected);
mBitmap = Utility.decodeBitmap(inputStream, 1280, 960);
photoArea.setImageBitmap(mBitmap);
sharePhotoBtn = (ImageView) findViewById(R.id.share_submit);
sharePhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBitmap != null && FormValidation.hasText(shareContent)) {
try {
File imageToShare = saveBitmapToStorage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareTxt = shareContent.getText().toString();
performPublish(PendingAction.POST_PHOTO);
//new FormSubmit(ctx,easyTracker).execute("shareImg",imageToShare, textToShare);
}
}
});
} else {
Toast.makeText(ctx, ctx.getResources().getString(R.string.get_photo_error), Toast.LENGTH_SHORT).show();
finish();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private File saveBitmapToStorage () throws IOException{
String path = Environment.getExternalStorageDirectory().toString();
File outputFile = new File(path, "temp.jpg");
FileOutputStream out = new FileOutputStream(outputFile);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
return outputFile;
}
//Facebook share
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(SharePicForm.this)
.setTitle(ctx.getResources().getString(R.string.error))
.setMessage(ctx.getResources().getString(R.string.get_permission_error))
.setPositiveButton(ctx.getResources().getString(R.string.close), null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they will succeed.
pendingAction = PendingAction.NONE;
if (previouslyPendingAction == PendingAction.POST_PHOTO)
postPhoto();
}
private void performPublish(PendingAction action) {
Log.d(TAG,"Perform publish");
Session session = Session.getActiveSession();
if (session != null) {
Log.d(TAG,"Session != null");
pendingAction = action;
if (hasPublishPermission()) {
Log.d(TAG,"Has permission");
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
Log.d(TAG,"Open session");
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "publish_actions"));
return;
} else {
onClickLogin();
}
} else{
Log.d(TAG,"Session == null");
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
} else {
Session.openActiveSession(this, true, callback);
}
}
private void postPhoto() {
Log.d(TAG,"postPhoto: " + hasPublishPermission());
if (hasPublishPermission()) {
if (mBitmap != null) {
Request request = Request.newUploadPhotoRequest(
Session.getActiveSession(),mBitmap, new Request.Callback() {
#Override
public void onCompleted(Response response) {
pd.dismiss();
if (response.getError() == null) {
Utility.showDialog(ctx,"success_photo",tracker);
} else {
Log.d(TAG,response.getError().getErrorMessage());
Toast.makeText(ctx, response.getError().getErrorMessage(), Toast.LENGTH_LONG).show();
Utility.showDialog(ctx,"error",tracker);
}
}
});
Bundle params = request.getParameters();
if (shareTxt != null)
params.putString("message", shareTxt);
request.setParameters(params);
request.executeAsync();
pd = ProgressDialog.show(ctx, ctx.getResources().getString(R.string.sys_info),ctx.getResources().getString(R.string.publishing));
}
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("bitmap", mBitmap);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(callback);
EasyTracker.getInstance(this).activityStart(this);
tracker.set(Fields.SCREEN_NAME, "Image_entryForm " + Utility.getLocale(this));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(callback);
EasyTracker.getInstance(this).activityStop(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(this,getResources().getString(R.string.app_id));
}
}
Should I implement the get user info code in all activities? thanks
Okay, Use below code.
//Define textview to print detail
TextView mfirstname, mlastname, middlename, mfullname, mbirthdate,
mfacebookLink, mfacebookId, mfacebookUnm, mgender, mEmail;
// Code to retrieve data from FB
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
mfirstname.setText(user.getFirstName());
mlastname.setText(user.getLastName());
middlename.setText(user.getMiddleName());
mfullname.setText(user.getName());
mbirthdate.setText(user.getBirthday());
mfacebookLink.setText(user.getLink());
mfacebookId.setText(user.getId());
mfacebookUnm.setText(user.getUsername());
String gender = user.asMap()
.get("gender").toString();
String email = user.asMap()
.get("email").toString();
mgender.setText(gender);
mEmail.setText(email);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});

Can't start another activity after Facebook login in android app

I have tried a lot to integrate facebook login in my android app. I have succeeded partially. Now my problem is I couldn't redirect to another activity after successful facebook login. I think it is because I called the activity not from a proper place. I mean I coudn't call activity before the session close. I have attached my code here.
public class FacebookLogin extends Activity {
private static List<String> permissions;
Session.StatusCallback statusCallback = new SessionStatusCallback();
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
// authButton.setFragment(this);
/***** FB Permissions *****/
permissions = new ArrayList<String>();
permissions.add("email");
/***** End FB Permissions *****/
authButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Check if there is any Active Session, otherwise Open New Session
Session session = Session.getActiveSession();
if(!session.isOpened()) {
session.openForRead(new Session.OpenRequest(FacebookLogin.this).setCallback(statusCallback).setPermissions(permissions));
} else {
Session.openActiveSession(FacebookLogin.this, true, statusCallback);
}
}
});
Session session = Session.getActiveSession();
if(session == null) {
if(savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if(session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
session.addCallback(statusCallback);
if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(permissions));
}
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
//Check if Session is Opened or not
processSessionStatus(session, state, exception);
}
}
#SuppressWarnings("deprecation")
public void processSessionStatus(Session session, SessionState state, Exception exception) {
if(session != null && session.isOpened()) {
if(session.getPermissions().contains("email")) {
//Show Progress Dialog
dialog = new ProgressDialog(FacebookLogin.this);
dialog.setMessage("Loggin in..");
dialog.show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (dialog!=null && dialog.isShowing()) {
dialog.dismiss();
}
if(user != null) {
Map<String, Object> responseMap = new HashMap<String, Object>();
GraphObject graphObject = response.getGraphObject();
responseMap = graphObject.asMap();
Log.i("FbLogin", "Response Map KeySet - " + responseMap.keySet());
// TODO : Get Email responseMap.get("email");
String fb_id = user.getId();
String email = null;
String name = (String) responseMap.get("name");
if (responseMap.get("email")!=null) {
email = responseMap.get("email").toString();
//TODO Login successfull Start your next activity
Intent intent = new Intent(FacebookLogin.this, UserAccount.class);
/*Sending some arguments*/
Bundle bundle = new Bundle();
bundle.putString("UserName",name );
bundle.putString("Id", email);
intent.putExtras(bundle);
startActivity(intent);
}
else {
//Clear all session info & ask user to login again
Session session = Session.getActiveSession();
if(session != null) {
session.closeAndClearTokenInformation();
}
}
}
}
});
} else {
session.requestNewReadPermissions(new Session.NewPermissionsRequest(FacebookLogin.this, permissions));
}
}
}
/********** Activity Methods **********/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FbLogin", "Result Code is - " + resultCode +"");
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
/*if(resultCode==RESULT_OK) {
Intent i = new Intent(FacebookLogin.this,UserAccount.class);
startActivity(i);
} */}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Save current session
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onStart() {
// TODO Add status callback
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
protected void onStop() {
// TODO Remove callback
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
Please help me..

facebook login Cannot pass a publish or manage permission (email) to a request for read authorization

I have a button click to login facebook,but sometimes this code can't work. throw exception:Caused by:
com.facebook.FacebookException: Cannot pass a publish or manage permission (email) to a request for read authorization
This is my activity's code :
public class FacebookLoginActivity extends Activity {
private final static String TAG="FB";
private static final List<String> PERMISSIONS=Arrays.asList("email", "user_likes", "user_status");
private Session.StatusCallback statusCallback=new SessionStatusCallback();
private GraphUser user = null;
private Bundle bundle;
private Intent myIntent;
private Session session;
private static FacebookLoginActivity instance=new FacebookLoginActivity();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(bundle==null){
bundle=new Bundle();
}
Log.v(TAG, "in FB onCreate method");
myIntent = this.getIntent();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
String action = ClientUtil.getElementValue("action");
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
session=openActiveSession(this, true, PERMISSIONS);
onClickLogin();
}
public void onClickLogin() {
Log.v(TAG, "click login btn");
session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
OpenRequest openRequest=new Session.OpenRequest(this);
openRequest.setPermissions(PERMISSIONS);
openRequest.setCallback(statusCallback);
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
session.openForPublish(openRequest);
} else {
Log.v(TAG, "open active session");
Session.openActiveSession(this, true, statusCallback);
}
}
#Override
public void onStart() {
super.onStart();
Log.v(TAG, "onStart method to add fb Callback");
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Log.v(TAG, "onStop method to remove fb callback");
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(TAG, "onActivityResult method to call Fb Session");
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session=Session.getActiveSession();
Session.saveSession(session, outState);
}
private static Session openActiveSession(Activity activity, boolean allowLoginUI, List<String> permissions) {
OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForPublish(openRequest);
return session;
}
return null;
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
Log.v(TAG, "in StatusCallback call method exception is:"+ exception);
Log.v(TAG, "session state is:"+session.isOpened());
if(user != null) {
Log.v(TAG, "fb user is exist todo login yyy");
login();
finish();
Log.v(TAG, "finish fb activity");
return;
}
if(session.isOpened()) {
Log.v(TAG, "session is opened to call FB Request");
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser me, Response response) {
Log.v(TAG, "in GraphUserCallback onCompleted method");
Log.v(TAG, "GraphUser has value:"+(user!=null));
if(me != null) {
user=me;
login();
}
finish();
Log.v(TAG, "finish fb activity");
}
});
}else{
Log.v(TAG, "session is not open");
if(exception !=null && exception.toString().contains("Canceled")){
Log.v(TAG, "cancle login");
bundle.putInt("code", RespondCode.CANCLE);
myIntent.putExtras(bundle);
setResult(Activity.RESULT_OK, myIntent);
finish();
}
}
}
}
}
You can't call openForPublish unless your app has already been granted basic permissions first.
Separate out your PERMISSIONS list into PERMISSIONS_READ and PERMISSIONS_PUBLISH, and put "email" into the PUBLISH side. Then call openForRead, and then requestNewPublishPermissions when your session is open.
Here is the thing you should do, it helped me in getting my requirement done:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLogin = (Button) findViewById(R.id.logIn);
mLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
// Do whatever u want. User has logged in
} else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) context);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(null);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
Session session = new Builder(MainActivity.this).build();
Session.setActiveSession(session);
session.openForPublish(op);
}
}
public void call(Session session, SessionState state, Exception exception) {
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello "
+ user.getName() + "!");
access_token = session
.getAccessToken();
firstName = user.getFirstName();
fb_user_id = user.getId();
System.out
.println("Facebook Access token: "
+ access_token);
System.out.println("First Name:"
+ firstName);
System.out.println("FB USER ID: "
+ fb_user_id);
}
}
});
}
}
});
}
}
Try the above code, it is just what you wanted to have.

Categories

Resources