Ejemplo n.º 1
0
  /* *
   * Called when invalidateOptionsMenu() is triggered
   */
  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    // if user not loggin, hide the action profile and logout
    boolean checkloggin = (session.isLoggedIn() && session != null);
    boolean checklogginFB = (sessionFacebook != null && sessionFacebook.isOpened());
    boolean check =
        (session != null && session.isLoggedIn())
            || (sessionFacebook != null && sessionFacebook.isOpened());
    menu.findItem(R.id.action_search).setVisible(!drawerOpen);
    menu.findItem(R.id.action_location_found).setVisible(!drawerOpen);
    menu.findItem(R.id.action_login).setVisible(!drawerOpen);
    menu.findItem(R.id.action_profile).setVisible(!drawerOpen);
    menu.findItem(R.id.action_logOut).setVisible(!drawerOpen);

    /*menu.findItem(R.id.action_profile).setVisible(checkloggin);
    menu.findItem(R.id.action_logOut).setVisible(checkloggin);
    menu.findItem(R.id.action_login).setVisible(!checkloggin);

    menu.findItem(R.id.action_logOut).setVisible(!checklogginFB);
    menu.findItem(R.id.action_profile).setVisible(!checklogginFB);
    menu.findItem(R.id.action_login).setVisible(checklogginFB);
      */
    // menu.findItem(R.id.action_profile).setVisible(check);
    menu.findItem(R.id.action_profile).setVisible(!checklogginFB);
    menu.findItem(R.id.action_profile).setVisible(checkloggin);
    menu.findItem(R.id.action_logOut).setVisible(check);
    menu.findItem(R.id.action_login).setVisible(!check);

    return super.onPrepareOptionsMenu(menu);
  }
Ejemplo n.º 2
0
  private static void finalizeLogin(
      Session session,
      SessionState state,
      Exception exception,
      final UnityMessage unityMessage,
      final Activity activityToClose) {
    if (activityToClose != null) {
      activityToClose.finish();
    }

    if (!session.isOpened() && state != SessionState.CLOSED_LOGIN_FAILED) {
      unityMessage.sendError("Unknown error while opening session. Check logcat for details.");
      return;
    }

    if (session.isOpened()) {
      unityMessage.put("opened", true);
    } else if (state == SessionState.CLOSED_LOGIN_FAILED) {
      unityMessage.putCancelled();
    }

    if (session.getAccessToken() == null || session.getAccessToken().equals("")) {
      unityMessage.send();
      return;
    }

    // there's a chance a subset of the permissions were allowed even if the login was cancelled
    // if the access token is there, try to get it anyways

    // add a callback to update the access token when it changes
    session.addCallback(
        new StatusCallback() {
          @Override
          public void call(Session session, SessionState state, Exception exception) {
            if (session == null || session.getAccessToken() == null) {
              return;
            }
            final UnityMessage unityMessage = new UnityMessage("OnAccessTokenUpdate");
            unityMessage.put("access_token", session.getAccessToken());
            unityMessage.put(
                "expiration_timestamp", "" + session.getExpirationDate().getTime() / 1000);
            unityMessage.send();
          }
        });
    unityMessage.put("access_token", session.getAccessToken());
    unityMessage.put("expiration_timestamp", "" + session.getExpirationDate().getTime() / 1000);
    Request.newMeRequest(
            session,
            new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                  unityMessage.put("user_id", user.getId());
                }
                unityMessage.send();
              }
            })
        .executeAsync();
  }
    @Override
    public void call(Session session, SessionState state, Exception exception) {
      Log.v("SessionStatusCallback", "call cbIndex:" + mCallbackIndex);
      Log.v("SessionStatusCallback", "state:" + state.toString());
      if (exception != null) Log.v("SessionStatusCallback", "exception:" + exception.toString());
      switch (mCallByMode) {
        case CallByLogin:
          if (session.isOpened()) {
            mCallByMode = CallByNull;
            // Date curDate = new Date();
            // Log.v(Tag,"getExpirationDate:"+(session.getExpirationDate().getTime()-curDate.getTime()));

            if (mCallbackIndex != -1)
              nativeCallback(
                  mCallbackIndex,
                  "{\"authResponse\":{\"accessToken\":\""
                      + session.getAccessToken()
                      + "\"},\"status\":\"connected\"}");
          } else if (state == SessionState.CLOSED_LOGIN_FAILED) {
            mCallByMode = CallByNull;
            if (mCallbackIndex != -1)
              nativeCallback(
                  mCallbackIndex, "{\"authResponse\":null,\"status\":\"not_authorized\"}");
          }
          break;
        case CallByLogout:
          if (session.isClosed()) {
            mCallByMode = CallByNull;
            if (mCallbackIndex != -1)
              nativeCallback(mCallbackIndex, "{\"authResponse\":{},\"status\":\"unknown\"}");
          }
          break;
        case CallByFBUI:
          {
            if (session.isOpened()) {
              mCallByMode = CallByNull;
              Message message = myHandler.obtainMessage(MyHandler.EXECUTE_WEBDIALOG, params);
              message.arg1 = mCallbackIndex;
              message.sendToTarget();
            } else if (state == SessionState.CLOSED_LOGIN_FAILED) {
              mCallByMode = CallByNull;
              if (mCallbackIndex != -1) nativeCallback(mCallbackIndex, "null");
            }
            break;
          }
        default:
          break;
      }
    }
Ejemplo n.º 4
0
  /** Diplaying fragment view for selected nav drawer list item */
  private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
      case 0:
        fragment = new PlanFragment();
        break;
      case 1:
        fragment = new FilterPlanFragment();
        break;
      case 2:
        if ((session != null && session.isLoggedIn())
            || (sessionFacebook != null && sessionFacebook.isOpened())) {
          fragment = new HistoryFragment();
        }
        // if(sessionFacebook.isClosed()){
        else {
          session.checkLogin();
        }
        break;
      case 3:
        if ((session != null && session.isLoggedIn())
            || (sessionFacebook != null && sessionFacebook.isOpened())) {
          fragment = new SettingFragment();
        }
        // if(sessionFacebook.isClosed()){
        else {
          session.checkLogin();
        }
        break;
      default:
        break;
    }

    if (fragment != null) {
      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

      // update selected item and title, then close the drawer
      mDrawerList.setItemChecked(position, true);
      mDrawerList.setSelection(position);
      setTitle(navMenuTitles[position]);
      mDrawerLayout.closeDrawer(mDrawerList);
    } else {
      // error in creating fragment
      Log.e("MainActivity", "Error in creating fragment");
    }
  }
Ejemplo n.º 5
0
  /** Get the current user profile info */
  private void makeMeRequest() {
    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
      Request request =
          Request.newMeRequest(
              session,
              new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                  isMakeMeRequestStarted = false;
                  dismissProgressDialog();

                  if (session == Session.getActiveSession() && user != null) {
                    mUser = user;
                    updateUI();
                  }
                  if (response != null && response.getError() != null) {
                    Utils.handleError(
                        getActivity(), response.getError(), Utils.getProfileReadPermission());
                  }
                }
              });
      request.executeAsync();
    }
  }
Ejemplo n.º 6
0
 private void onSessionStateChange(
     final Session session, SessionState state, Exception exception) {
   if (session != null && session.isOpened()) {
     // Get the user's data.
     makeMeRequest(session);
   }
 }
Ejemplo n.º 7
0
 @Override
 public void call(Session session, SessionState state, Exception exception) {
   if (session != null && session.isOpened()) {
     if (AccountActivity.accountImages != null
         && AccountActivity.accountListViewAdapter != null) {
       AccountActivity.accountImages[0] = R.drawable.fb_blue;
       AccountActivity.accountListViewAdapter.getItem(0).setItemImageId(R.drawable.fb_blue);
       AccountActivity.accountListViewAdapter.notifyDataSetChanged();
     }
     SharedPreferenceUtil.put(
         SharedPreferenceUtil.PREF_FACEBOOK_TOKEN, session.getAccessToken());
     SharedPreferenceUtil.put(
         SharedPreferenceUtil.PREF_FACEBOOK_EXPIRE_DATE,
         dateFormat.format(session.getExpirationDate()));
   } else {
     if (AccountActivity.accountImages != null
         && AccountActivity.accountListViewAdapter != null) {
       AccountActivity.accountImages[0] = R.drawable.fb_white;
       AccountActivity.accountListViewAdapter.getItem(0).setItemImageId(R.drawable.fb_white);
       AccountActivity.accountListViewAdapter.notifyDataSetChanged();
     }
     SharedPreferenceUtil.removeValue(SharedPreferenceUtil.PREF_FACEBOOK_TOKEN);
     SharedPreferenceUtil.removeValue(SharedPreferenceUtil.PREF_FACEBOOK_EXPIRE_DATE);
   }
 }
Ejemplo n.º 8
0
 public static boolean isOpen() {
   Session session = Session.getActiveSession();
   if (session != null && session.isOpened()) {
     return true;
   }
   return false;
 }
Ejemplo n.º 9
0
 private void openSession(
     String applicationId,
     List<String> permissions,
     SessionLoginBehavior behavior,
     int activityCode,
     SessionAuthorizationType authType) {
   if (sessionTracker != null) {
     Session currentSession = sessionTracker.getSession();
     if (currentSession == null || currentSession.getState().isClosed()) {
       Session session =
           new Session.Builder(getActivity()).setApplicationId(applicationId).build();
       Session.setActiveSession(session);
       currentSession = session;
     }
     if (!currentSession.isOpened()) {
       Session.OpenRequest openRequest =
           new Session.OpenRequest(this)
               .setPermissions(permissions)
               .setLoginBehavior(behavior)
               .setRequestCode(activityCode);
       if (SessionAuthorizationType.PUBLISH.equals(authType)) {
         currentSession.openForPublish(openRequest);
       } else {
         currentSession.openForRead(openRequest);
       }
     }
   }
 }
Ejemplo n.º 10
0
 private void fetchUserInfo() {
   final Session currentSession = getSession();
   if (currentSession != null && currentSession.isOpened()) {
     if (currentSession != userInfoSession) {
       Request request =
           Request.newMeRequest(
               currentSession,
               new Request.GraphUserCallback() {
                 @Override
                 public void onCompleted(GraphUser me, Response response) {
                   if (currentSession == getSession()) {
                     user = me;
                     updateUI();
                   }
                   if (response.getError() != null) {
                     loginButton.handleError(response.getError().getException());
                   }
                 }
               });
       Bundle parameters = new Bundle();
       parameters.putString(FIELDS, REQUEST_FIELDS);
       request.setParameters(parameters);
       Request.executeBatchAsync(request);
       userInfoSession = currentSession;
     }
   } else {
     user = null;
   }
 }
  private void initUI() {
    aQuery
        .id(R.id.logout_button)
        .clicked(
            new OnClickListener() {

              @Override
              public void onClick(View v) {
                Session session = Session.getActiveSession();
                if (!session.isClosed()) {
                  session.closeAndClearTokenInformation();
                  Intent mainIntent = new Intent(getActivity(), LoginActivity.class);
                  mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  pref.edit().remove(Common.USER_ID).commit();
                  startActivity(mainIntent);
                }
              }
            });

    Session session = Session.getActiveSession();
    if (session.isOpened()) {
      Request.executeMeRequestAsync(
          session,
          new GraphUserCallback() {

            @Override
            public void onCompleted(GraphUser user, Response response) {
              mProfilePictureView.setProfileId(user.getId());
              aQuery.id(R.id.profile_username_textview).text(user.getName());
            }
          });
    }

    initList();
  }
Ejemplo n.º 12
0
  private void updateView() {
    Session session = Session.getActiveSession();
    if (session.isOpened()) {
      // Check for publish permissions
      List<String> permissions = session.getPermissions();
      if (!isSubsetOf(PERMISSIONS, permissions)) {
        Session.NewPermissionsRequest newPermissionsRequest =
            new Session.NewPermissionsRequest(this, PERMISSIONS);
        session.requestNewPublishPermissions(newPermissionsRequest);
      }

      makeMeRequest(session);

      // bLoginFacebook.setText(R.string.Log_Out);
      bLoginFacebook.setOnClickListener(
          new OnClickListener() {
            public void onClick(View view) {
              onClickLogout();
            }
          });
    } else {
      // bLoginFacebook.setText(R.string.Log_In);
      bLoginFacebook.setOnClickListener(
          new OnClickListener() {
            public void onClick(View view) {
              onClickLogin();
            }
          });
    }
  }
Ejemplo n.º 13
0
  private void updateUI() {
    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());

    // postStatusUpdateButton.setEnabled(enableButtons
    // || canPresentShareDialog);
    // postPhotoButton.setEnabled(enableButtons
    // || canPresentShareDialogWithPhotos);
    // pickFriendsButton.setEnabled(enableButtons);
    // pickPlaceButton.setEnabled(enableButtons);
    //
    if (enableButtons && user != null) {
      System.out.println("userid" + user.getId());
      System.out.println("First name" + user.getFirstName());
      System.out.println("email" + user.getProperty("email").toString());
      System.out.println("Birthday:" + user.getBirthday());
      System.out.println("GENDER" + user.getBirthday());
      System.out.println("Location:" + user.getLocation());

      System.out.println("JSON:" + user.getInnerJSONObject());

    } else {
      System.out.println("Userinfo is null");
    }
  }
 public static void getLoginStatus(int cbIndex, boolean force) {
   Log.v(TAG, "getLoginStatus" + cbIndex);
   Session session = Session.getActiveSession();
   if (session == null) {
     nativeCallback(cbIndex, "{\"authResponse\":null,\"status\":\"unknown\"}");
   } else {
     if (session.isOpened()) {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"connected\"}");
     } else if (session.getState() == SessionState.CLOSED_LOGIN_FAILED) {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"not_authorized\"}");
     } else {
       nativeCallback(
           cbIndex,
           "{\"authResponse\":{\"accessToken\":\""
               + session.getAccessToken()
               + "\"},\"status\":\"unknown\"}");
     }
   }
 }
Ejemplo n.º 15
0
 private void onClickLogin() {
   Session session = Session.getActiveSession();
   if (!session.isOpened() && !session.isClosed()) {
     session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
   } else {
     Session.openActiveSession(this, true, statusCallback);
   }
 }
Ejemplo n.º 16
0
  @Override
  protected void onResumeFragments() {
    super.onResumeFragments();
    Session session = Session.getActiveSession();

    if (session != null && session.isOpened()) showFragment(SELECTION, false);
    else showFragment(SPLASH, false);
  }
Ejemplo n.º 17
0
  private void login(JSONArray args, CallbackContext callbackContext) throws JSONException {
    Session session = Session.getActiveSession();

    if (session == null || session.isClosed()) {
      Log.d(TAG, "Building new session");
      session = new Session.Builder(cordova.getActivity()).setApplicationId(this.appId).build();
      Session.setActiveSession(session);
    } else {
      Log.d(TAG, "Existing session " + session.getState());
    }

    if (session.isOpened()) {
      Log.d(TAG, "Session already open");
      callbackContext.success(buildAuthorizationResponse(session));
      return;
    }

    final CallbackContext callback = callbackContext;

    List<String> permissions = new ArrayList<String>();

    permissions.add("basic_info");
    JSONArray argumentPermissions = args.getJSONArray(0);

    for (int i = 0; i < argumentPermissions.length(); i++) {
      permissions.add(argumentPermissions.getString(i));
    }

    OpenRequest openRequest =
        new OpenRequest(cordova.getActivity())
            .setPermissions(permissions)
            .setCallback(
                new StatusCallback() {
                  @Override
                  public void call(Session session, SessionState state, Exception exception) {
                    Log.d(TAG, "In status callback open for read " + state);

                    if (state == SessionState.OPENING) {
                      return;
                    }

                    session.removeCallback(this);

                    try {
                      JSONObject response = buildAuthorizationResponse(session);

                      callback.success(response);
                    } catch (JSONException e) {
                      Log.e(TAG, "JSONException", e);
                      callback.error(e.toString());
                    }
                  }
                });

    cordova.setActivityResultCallback(this);

    session.openForRead(openRequest);
  }
Ejemplo n.º 18
0
 public void onClickLogin() {
   Session session = Session.getActiveSession();
   if (!session.isOpened() && !session.isClosed()) {
     session.openForRead(
         new Session.OpenRequest(mContext).setPermissions(this.mPermissions).setCallback(this));
   } else {
     Session.openActiveSession(mContext, true, this);
   }
 }
Ejemplo n.º 19
0
 public void loginWithFacebook() {
   //  TipsManager.setIsJustLogined(true);
   Session session = Session.getActiveSession();
   if (!session.isOpened() && !session.isClosed()) {
     session.openForRead(new Session.OpenRequest(activity).setCallback(facebookStatusCallback));
   } else {
     Session.openActiveSession(activity, true, facebookStatusCallback);
   }
 }
  public static String api(String graphPath, String method, String params, int cbIndex) {
    Log.v(TAG, "api-graphPath:" + graphPath);

    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
      HttpMethod httpMethod = HttpMethod.GET;
      if (method != null) {
        if (method.compareTo("post") == 0) httpMethod = HttpMethod.POST;
        else if (method.compareTo("delete") == 0) httpMethod = HttpMethod.DELETE;
      }

      Bundle parameters = new Bundle();
      try {
        if (params != null) {
          JSONObject jsonObject = new JSONObject(params);
          Iterator<String> iterator = jsonObject.keys();
          String key = null;
          String value = null;
          while (iterator.hasNext()) {
            key = iterator.next();
            Object object = jsonObject.get(key);
            if (object instanceof String) {
              value = (String) object;
              if (key.compareTo("method") != 0) parameters.putString(key, value);
            } else if (object instanceof Integer) {
              parameters.putInt(key, ((Integer) object).intValue());
            } else if (object instanceof Boolean) {
              parameters.putBoolean(key, ((Boolean) object).booleanValue());
            } else if (object instanceof Double) {
              parameters.putDouble(key, ((Double) object).doubleValue());
            } else {
              Log.w(TAG, "other type:" + object.toString());
            }
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }

      Request request =
          new Request(
              session,
              graphPath,
              parameters,
              httpMethod,
              new FacebookConnectPlugin.RequestCallback(cbIndex));
      Message message = myHandler.obtainMessage(MyHandler.EXECUTE_REQUEST, request);

      message.sendToTarget();
    } else {
      return "{\"message\":\"An active access token must be used to query information about the current user.\""
          + ",\"type\":\"OAuthException\",\"code\": 2500}";
    }
    return null;
  }
Ejemplo n.º 21
0
  private void getAccessToken(CallbackContext callbackContext) throws JSONException {
    Session session = Session.getActiveSession();
    JSONObject response = new JSONObject();

    if (session == null || !session.isOpened()) {
      response.put("error", "not_authorized");
    } else {
      response.put("accessToken", session.getAccessToken());
    }

    callbackContext.success(response);
  }
Ejemplo n.º 22
0
 @Override
 protected void onResume() {
   super.onResume();
   // For scenarios where the main activity is launched and user
   // session is not null, the session state change notification
   // may not be triggered. Trigger it if it's open/closed.
   Session session = Session.getActiveSession();
   if (session != null && (session.isOpened() || session.isClosed())) {
     onSessionStateChange(session, session.getState(), null);
   }
   uiHelper.onResume();
 }
Ejemplo n.º 23
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.item_details);

    Intent intent = getIntent();
    disk = (Disk) intent.getSerializableExtra("disk");

    if (intent.hasExtra("fbusername")) {
      fbusername = intent.getStringExtra("fbusername");
    } else {
      fbusername = "******";
    }

    title = (TextView) findViewById(R.id.textView1);
    artist = (TextView) findViewById(R.id.artist);
    status = (TextView) findViewById(R.id.status);
    diskImage = (ImageView) findViewById(R.id.disk_image);

    title.setText(disk.getTitle());
    artist.setText(disk.getArtist());
    status.setText(disk.getStatus());

    // Set up image in view
    byte[] imageAsBytes = Base64.decode(disk.getImageEncoding(), Base64.DEFAULT);
    diskImage.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

    // Find the user's profile picture custom view
    profilePictureView = (ProfilePictureView) findViewById(R.id.item_details_profile_pic);
    profilePictureView.setCropped(false);
    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
      // Get the user's data
      makeMeRequest(session);
    }

    // Set up action that will be triggered when user presses the Send button
    ((Button) findViewById(R.id.button2))
        .setOnClickListener(
            new OnClickListener() {
              public void onClick(View view) {
                send_message();
              }
            });

    // Set up action that will be triggered when user presses the Home button
    ((ImageButton) findViewById(R.id.home))
        .setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View view) {
                go_home();
              }
            });
  }
Ejemplo n.º 24
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alubumlistview);
    alubumlistview = (ListView) findViewById(R.id.alubumlistview);
    imagegallerytextview = (TextView) findViewById(R.id.imagegallerytextview);
    Ultilities mUltilities = new Ultilities();
    int imageHeightAndWidht[] = mUltilities.getImageHeightAndWidthForAlubumListview(this);
    alubumList = new ArrayList<ListviewAlubumData>();
    mAlubumListViewAdapter = new AlubumListViewAdapter(this, alubumList, imageHeightAndWidht);
    alubumlistview.setAdapter(mAlubumListViewAdapter);
    imagegallerytextview.setText("Albums");
    Typeface HelveticaLTStd_Light =
        Typeface.createFromAsset(getAssets(), "fonts/HelveticaLTStd-Light.otf");
    imagegallerytextview.setTypeface(HelveticaLTStd_Light);
    imagegallerytextview.setTextColor(Color.rgb(255, 255, 255));
    imagegallerytextview.setTextSize(20);
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    Session session = Session.getActiveSession();

    logDebug("onCreate session " + session);
    if (session == null) { // logDebug("onCreate savedInstanceState "+savedInstanceState);
      if (savedInstanceState != null) {
        session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
        // logDebug("onCreate savedInstanceState restore session   "+session);
      }
      if (session == null) {
        session = new Session(this);
        // logDebug("onCreate savedInstanceState create session   "+session);
      }
      Session.setActiveSession(session);
      // logDebug("onCreate savedInstanceState state session    "+session.getState());
      if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        // session.openForRead(new
        // Session.OpenRequest(this).setPermissions(Arrays.asList("user_birthday",
        // "email","user_relationships","user_photos")).setCallback(statusCallback));
      }
    }

    try {
      if (session.isOpened()) {
        getUserAllAlubum();
      } else {
        getOpenedSession();
      }
      alubumlistview.setOnItemClickListener(this);
      ;

    } catch (Exception e) {
      logError("error onCreate Exception " + e);
    }
  }
Ejemplo n.º 25
0
  public void publishFeedDialog(
      String name, String caption, String description, String link, String picture) {

    final Context context = UtilActivity.this;
    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {

      Bundle params = new Bundle();
      params.putString("name", name);
      params.putString("caption", caption);
      params.putString("description", description);
      params.putString("link", link);
      params.putString("picture", picture);

      WebDialog feedDialog =
          (new WebDialog.FeedDialogBuilder(context, 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(context, "Posted story, id: " + postId, Toast.LENGTH_SHORT)
                              .show();
                        } else {
                          // User clicked the Cancel button
                          Toast.makeText(context, "Publish cancelled", Toast.LENGTH_SHORT).show();
                        }
                      } else if (error instanceof FacebookOperationCanceledException) {
                        // User clicked the "x" button
                        Toast.makeText(context, "Publish cancelled", Toast.LENGTH_SHORT).show();
                      } else {
                        // Generic, ex: network error
                        Toast.makeText(context, "Error posting story", Toast.LENGTH_SHORT).show();
                      }
                    }
                  })
              .build();
      feedDialog.show();

    } else {

      AlertDialog.Builder builder = new AlertDialog.Builder(context);
      builder.setMessage("Facebook app not available.");
      builder.setNeutralButton(context.getResources().getString(android.R.string.ok), null);
      builder.create().show();
    }
  }
Ejemplo n.º 26
0
 protected void onSessionStateChange(Session session, SessionState state, Exception exception) {
   LogUtil.e("go into facebook status call back");
   if (exception != null && mAction != PendingAction.NONE) {
     DialogUtil.createMsgDialog(this, exception.getMessage(), getString(R.string.confirm)).show();
     mAction = PendingAction.NONE;
     return;
   }
   if (session.isOpened()) {
     if (mAction != PendingAction.NONE) {
       performAction();
     }
   }
 }
 public void onResume() {
   // For scenarios where the main activity is launched and user
   // session is not null, the session state change notification
   // may not be triggered. Trigger it if it's open/closed.
   Session session = Session.getActiveSession();
   if (session != null && (session.isOpened() || session.isClosed())) {
     if (session.getState().isOpened()) {
       Log.i(TAG, "Logged in...");
     } else if (session.getState().isClosed()) {
       Log.i(TAG, "Logged out...");
     }
   }
   uiHelper.onResume();
 }
Ejemplo n.º 28
0
  // event handler del boton like
  public void like(View v) {
    // aqui el codigo que se ejucuta cuando se pulsa al buton "i like this plan" porque
    // en fragment_activity.xml he hecho android:onClick="like"

    if ((session != null && session.isLoggedIn())
        || (sessionFacebook != null && sessionFacebook.isOpened())) {
      // Intent i = new Intent(MainActivity.this, Profile.class);
      // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      // startActivity(i);
      Toast.makeText(getApplicationContext(), "UNDER CONSTRUCTION", Toast.LENGTH_SHORT).show();

    } else {
      session.checkLogin();
    }
  }
 private boolean validatePermissions(
     List<String> permissions, SessionAuthorizationType authType, Session currentSession) {
   if (SessionAuthorizationType.PUBLISH.equals(authType)) {
     if (Utility.isNullOrEmpty(permissions)) {
       throw new IllegalArgumentException(
           "Permissions for publish actions cannot be null or empty.");
     }
   }
   if (currentSession != null && currentSession.isOpened()) {
     if (!Utility.isSubset(permissions, currentSession.getPermissions())) {
       Log.e(TAG, "Cannot set additional permissions when session is already open.");
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 30
0
  private void updateUI() {
    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());

    postStatusUpdateButton.setEnabled(enableButtons);
    postPhotoButton.setEnabled(enableButtons);
    pickFriendsButton.setEnabled(enableButtons);
    pickPlaceButton.setEnabled(enableButtons);

    if (enableButtons && user != null) {
      profilePictureView.setProfileId(user.getId());
      greeting.setText("Greetings " + user.getFirstName());
    } else {
      profilePictureView.setProfileId(null);
      greeting.setText(null);
    }
  }