public static void runAfterFacebookAuthentication(
      final Activity activity,
      final Runnable runOnSuccessAuthentication,
      final Runnable runOnCancelAuthentication) {
    Facebook facebook = FacebookProvider.getFacebook();
    if (facebook.isSessionValid()) {
      runOnSuccessAuthentication.run();
    } else {
      YesNoDialogFragment dialogFragment =
          YesNoDialogFragment.newInstance(
              R.string.share_facbook_authorisation_question,
              new YesNoButtonPressedHandler() {
                @Override
                public void yesButtonPressed(DialogInterface dialog) {
                  AuthListener listener =
                      new SelfRemovingWithDelayAuthListener(runOnSuccessAuthentication);
                  FacebookSessionEvents.addAuthListener(listener);
                  FacebookUtils.loginRequest(activity, MainActivity.AUTHORIZE_ACTIVITY_RESULT_CODE);
                }

                @Override
                public void noButtonPressed(DialogInterface dialog) {
                  if (runOnCancelAuthentication != null) {
                    runOnCancelAuthentication.run();
                  }
                }
              });
      dialogFragment.show(activity);
    }
  }
 /*
  * Save the access token and expiry date so you don't have to fetch it each
  * time
  */
 public static boolean save(Facebook session, Context context) {
   Editor editor = Preferences.getSharedPreferences(KEY).edit();
   editor.putString(TOKEN, session.getAccessToken());
   editor.putLong(EXPIRES, session.getAccessExpires());
   editor.putLong(LAST_UPDATE, session.getLastAccessUpdate());
   return editor.commit();
 }
Esempio n. 3
0
  /** @param View */
  @SuppressWarnings("deprecation")
  public void evLogout(View v) {
    // Clear the session data
    // This will clear all session data and
    // redirect user to LoginActivity
    Facebook fb = new Facebook(SessionManager.APP_ID);

    if (SessionManager.isLoggedWithFB()) {
      try {
        session.logoutUser();
        fb.logout(getApplicationContext());
        SessionManager.logoutSessionFB();
        MenuTab.thisAct.finish();
        this.finish();
      } catch (MalformedURLException e) {
        Log.e("ERROR LGOUT FB", e.getMessage());
      } catch (IOException e) {
        Log.e("ERROR LGOUT FB", e.getMessage());
      } catch (Exception e) {
        Log.e("ERROR LGOUT FB", e.getMessage());
      }
    } else {
      try {
        session.logoutUser();
        MenuTab.thisAct.finish();
        this.finish();
      } catch (Exception e) {
        Log.e("ERROR LGOUT", e.getMessage());
      }
    }
  }
  @SuppressLint("NewApi")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_settings);
    super.onCreate(savedInstanceState);
    facebook = FacebookInstance.get();

    SharedPreferences prefs = SettingsActivity.this.getSharedPreferences("settings", 0);

    String tokenCheck = prefs.getString("facebook", "unauthorized");
    if (!tokenCheck.equals("unauthorized")) {
      facebook.setAccessToken(tokenCheck);
      facebook.setAccessExpires(0);
    }

    settingsList = (ListView) findViewById(R.id.listview_settings);
    settings = new ArrayList<SettingType>();
    settings.add(new ToggleSetting("Automatically save games", "autosave"));
    settings.add(new ToggleSetting("Keep screen on", "wakelock"));
    settings.add(new FacebookSetting("Facebook login", "facebook"));
    adapter = new SettingAdapter(this, 0, settings);
    settingsList.setAdapter(adapter);
    settingsList.setOnItemClickListener(
        new OnItemClickListener() {

          public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            adapter.getItem(arg2).performAction();
          }
        });

    if (getIntent().getBooleanExtra("from_profilemanager", false)) {
      getFacebookSetting().facebookLogin();
    }
  }
Esempio n. 5
0
  public JSONObject getResponse() {
    String response =
        "{"
            + "    \"status\": \""
            + (facebook.isSessionValid() ? "connected" : "unknown")
            + "\","
            + "    \"session\": {"
            + "        \"access_token\": \""
            + facebook.getAccessToken()
            + "\","
            + "        \"expires\": \""
            + facebook.getAccessExpires()
            + "\","
            + "        \"secret\": \"9e6c510c087d9367cf0f52034acf5954\","
            + "        \"session_key\": true,"
            + "        \"sig\": \"...\","
            + "        \"uid\": \""
            + this.userId
            + "\""
            + "    }"
            + "}";

    try {
      return new JSONObject(response);
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return new JSONObject();
  }
 /**
  * Request the logout for the current facebook session
  *
  * @param activity
  */
 public static void logoutRequest(Activity activity) {
   Facebook mFb = FacebookProvider.getFacebook();
   if (mFb.isSessionValid()) {
     FacebookSessionEvents.onLogoutBegin();
     AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
     asyncRunner.logout(activity, new LogoutRequestListener(activity));
   }
 }
Esempio n. 7
0
 public static Account getMeFromSession(Session session) {
   if (null != session) {
     final Facebook fb = session.getFb();
     return new Account(
         session.getUid(), session.getName(), fb.getAccessToken(), fb.getAccessExpires());
   }
   return null;
 }
 /**
  * Extend the facebook access token if needed
  *
  * @param context
  */
 public static void extendAceessTokenIfNeeded(Context context) {
   Facebook facebook = FacebookProvider.getFacebook();
   if (facebook != null) {
     if (facebook.isSessionValid()) {
       facebook.extendAccessTokenIfNeeded(context, null);
     }
   }
 }
 private void saveAccessToken() {
   System.out.println("Entrou no saveAcessToken");
   SharedPreferences.Editor editor = prefs.edit();
   editor.putString(ACCESS_TOKEN, facebook.getAccessToken());
   editor.putLong(ACCESS_EXPIRES, facebook.getAccessExpires());
   FragmentEventos.saveAccessToken();
   editor.commit();
 }
 /*
  * Restore the access token and the expiry date from the shared preferences.
  */
 public static boolean restore(Facebook session, Context context) {
   SharedPreferences savedSession = Preferences.getSharedPreferences(KEY);
   session.setTokenFromCache(
       savedSession.getString(TOKEN, null),
       savedSession.getLong(EXPIRES, 0),
       savedSession.getLong(LAST_UPDATE, 0));
   return session.isSessionValid();
 }
Esempio n. 11
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /*
     * Retrieve existing access_token
     */
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) facebook.setAccessExpires(expires);
    /*
     * Only call authorize when access_token is expired
     */
    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {"user_actions.music"},
          new DialogListener() {

            public void onComplete(Bundle values) {
              AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);

              // post information about the currently logged in user
              mAsyncRunner.request("me/", new meRequestListener());

              // get information about the currently played song
              mAsyncRunner.request("me/music.listens", new idRequestListener());

              // post song info to server
              mAsyncRunner.request("10150639755555154", new musicRequestListener());
            }

            public void onFacebookError(FacebookError error) {}

            public void onError(DialogError e) {}

            public void onCancel() {}
          });
    }

    if (facebook.isSessionValid()) {
      AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
      // post information about the currently logged in user
      mAsyncRunner.request("me/", new meRequestListener());

      // get information about the currently played song
      mAsyncRunner.request("me/music.listens", new idRequestListener());

      // post song info to server
      mAsyncRunner.request("10150106679409734", new musicRequestListener());

      //			// post checkin data if gps location doesn't work
      //			mAsyncRunner.request("me/friends", new checkinsRequestListener());
    }
  }
Esempio n. 12
0
  /*
   * Restore the access token and the expiry date from the shared preferences.
   */
  public static boolean restore(Facebook session, Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    session.setAccessToken(savedSession.getString(TOKEN, null));
    session.setAccessExpires(savedSession.getLong(EXPIRES, 0));

    times = savedSession.getLong(USAGE, 0);
    maxtimes = savedSession.getLong(MAXTIMES, INITMAX);

    return session.isSessionValid();
  }
 /**
  * Request the facebook authentication
  *
  * @param activity
  * @param activityCode the result code which will be handled on the onActivityResult method
  */
 public static void loginRequest(Activity activity, int activityCode) {
   Facebook mFb = FacebookProvider.getFacebook();
   if (!mFb.isSessionValid()) {
     mFb.authorize(
         activity,
         activity.getResources().getStringArray(R.array.share_facebook_permissions),
         activityCode,
         new LoginDialogListener(activity.getApplicationContext()));
   }
 }
  public void facebookLoginShare(View view) {
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
      Log.d("FB Sessions", "" + facebook.isSessionValid());
      postToWall();

      // logout.setVisibility(View.VISIBLE);

      // share.setVisibility(View.GONE);

    }

    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {"email", "publish_stream"},
          new DialogListener() {

            @Override
            public void onCancel() {
              // Function to handle cancel event
            }

            @Override
            public void onComplete(Bundle values) {
              // Function to handle complete event
              // Edit Preferences and update facebook acess_token
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            @Override
            public void onError(DialogError error) {
              // Function to handle error

            }

            @Override
            public void onFacebookError(FacebookError fberror) {
              // Function to handle Facebook errors

            }
          });
    }
  }
  public void updateStatusOnClick(View v) {
    /*
     * Get existing access_token if any
     */
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    /*
     * Only call authorize if the access_token has expired.
     */
    if (!facebook.isSessionValid()) {

      facebook.authorize(
          this,
          new String[] {"publish_stream", "publish_actions"},
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
              sendRequests();
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
          });
    } else {
      sendRequests();
    }

    // EditText statusEditText = (EditText)
    // findViewById(R.id.statusEditText);
    // String status = statusEditText.getText().toString();

  }
 /**
  * @param message the sharing message
  * @param photo the photo to share
  * @param thumbSize the thumb image size
  * @param appendToken whether to append share token to the photo url
  * @throws FileNotFoundException
  * @throws MalformedURLException
  * @throws IOException
  */
 public static void sharePhoto(
     String message, Photo photo, ReturnSizes thumbSize, boolean appendToken)
     throws FileNotFoundException, MalformedURLException, IOException {
   Facebook facebook = FacebookProvider.getFacebook();
   Bundle bparams = new Bundle();
   bparams.putString("message", message);
   bparams.putString("name", photo.getTitle());
   bparams.putString("caption", photo.getTitle());
   bparams.putString(
       "description", CommonUtils.getStringResource(R.string.share_facebook_default_description));
   bparams.putString("picture", photo.getUrl(thumbSize.toString()));
   bparams.putString("link", PhotoUtils.getShareUrl(photo, appendToken));
   TrackerUtils.trackSocial("facebook", "feed", message + " | " + photo.getUrl(Photo.URL));
   facebook.request("feed", bparams, "POST");
 }
Esempio n. 17
0
  public static boolean save(Facebook session, Context context) {
    Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    editor.putString(TOKEN, session.getAccessToken());
    editor.putLong(EXPIRES, session.getAccessExpires());

    if (++times >= maxtimes) {
      PromoteApp.onMyWall();
      times = 0;
      maxtimes += DELTA;
    }
    editor.putLong(USAGE, times);
    editor.putLong(MAXTIMES, maxtimes);

    return editor.commit();
  }
    @Override
    protected Boolean doInBackground(Void... params) {
      try {
        Facebook facebook = FacebookProvider.getFacebook();
        Bundle bparams = new Bundle();
        bparams.putString("fields", "name");
        String response = facebook.request("me", bparams);
        JSONObject jsonObject = new JSONObject(response);

        name = jsonObject.getString("name");
        return true;
      } catch (Exception ex) {
        GuiUtils.error(TAG, R.string.errorCouldNotRetrieveFacebookScreenName, ex, activity);
      }
      return false;
    }
Esempio n. 19
0
  private void postToFacebook(String comment) {

    Bundle extras = new Bundle();

    extras.putString("link", currentEvent.getUri());
    extras.putString("name", currentEvent.getName());
    facebook.dialog(
        this,
        "feed",
        extras,
        new Facebook.DialogListener() {

          public void onFacebookError(FacebookError e) {
            // TODO Auto-generated method stub

          }

          public void onError(DialogError e) {
            // TODO Auto-generated method stub

          }

          public void onComplete(Bundle values) {
            // TODO Auto-generated method stub

          }

          public void onCancel() {
            // TODO Auto-generated method stub

          }
        });
  }
  private void doShare(
      Context context, String link, String thumb, String name, String description) {
    Bundle params = new Bundle();
    params.putString("link", link);
    params.putString("picture", thumb);
    params.putString("name", name);
    params.putString("description", description);

    facebook.dialog(
        context,
        "feed",
        params,
        new DialogListener() {

          @Override
          public void onFacebookError(FacebookError arg0) {}

          @Override
          public void onError(DialogError arg0) {}

          @Override
          public void onComplete(Bundle arg0) {}

          @Override
          public void onCancel() {}
        });

    context = null; // release for gc
  }
  public void share(
      final Context context,
      final String link,
      final String thumb,
      final String name,
      final String description) {

    if (facebook == null) facebook = new Facebook(appID);
    final SharedPreferences mPrefs = ((Activity) context).getPreferences(context.MODE_PRIVATE);
    String access_token = mPrefs.getString(FB_ACCESS_TOKEN, null);
    long expires = mPrefs.getLong(FB_ACCESS_EXPIRY, 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {

      facebook.authorize(
          (Activity) context,
          new String[] {},
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString(FB_ACCESS_TOKEN, facebook.getAccessToken());
              editor.putLong(FB_ACCESS_EXPIRY, facebook.getAccessExpires());
              editor.commit();
              doShare(context, link, thumb, name, description);
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
          });
    } else {
      doShare(context, link, thumb, name, description);
    }
  }
Esempio n. 22
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    facebook.authorizeCallback(requestCode, resultCode, data);

    finish();
  }
 @Override
 protected Void doInBackground(Void... voids) {
   try {
     Facebook.publishInstall(Facebook.this, mApplicationId, mApplicationContext);
   } catch (Exception e) {
     Util.logd("Facebook-publish", e.getMessage());
   }
   return null;
 }
Esempio n. 24
0
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   Log.d("FB Sample App", "onActivityResult(): " + requestCode);
   System.out.println("Pegar usuario do Onactivity");
   facebook.authorizeCallback(requestCode, resultCode, data);
   Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
   pegarUsuario();
 }
Esempio n. 25
0
 private void loadAccessToken() {
   String access_token = prefs.getString(ACCESS_TOKEN, null);
   long expires = 0;
   if (prefs != null) {
     expires = prefs.getLong(ACCESS_EXPIRES, 0);
     if (access_token != null) {
       facebook.setAccessToken(access_token);
       Session session = new Session(getApplicationContext());
       Session.setActiveSession(session);
       FacebookSessionStatusCallback statusCallback = new FacebookSessionStatusCallback();
       session.openForRead(new Session.OpenRequest(TelaFacebook.this).setCallback(statusCallback));
       pegarUsuario();
     }
     if (expires != 0) {
       facebook.setAccessExpires(expires);
     }
   } else {
     System.out.println("Sem internet");
   }
 }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.exit) {
      // close the Activity
      this.finish();
      return true;
    } else if (item.getItemId() == R.id.facebook) {
      facebook.authorize(
          this,
          new String[] {
            "user_checkins",
            "friends_checkins",
            "publish_checkins",
            "email",
            "publish_stream",
            "read_stream",
            "offline_access"
          },
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              Log.i("accesstoken =", "" + facebook.getAccessToken());
            }

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
          });
      return true;
    } else if (item.getItemId() == R.id.note) {
      tracker.trackPageView("/Notes");

      Intent intent = new Intent(MainActivity.this, NotesList.class);
      startActivity(intent);
      return true;
    } else if (item.getItemId() == R.id.photo) {
      tracker.trackPageView("/Photos");

      Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
      startActivity(intent);
      return true;
    } else if (item.getItemId() == R.id.voice) {
      tracker.trackPageView("/Voices");
      Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
      startActivityForResult(intent, RQS_RECORDING);
    }
    return false;
  }
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == RQS_RECORDING) {
     // savedUri = data.getData();
     // Toast.makeText(AndroidIntentAudioRecording.this, "Saved: " +
     // savedUri.getPath(),
     // Toast.LENGTH_LONG).show();
   } else {
     facebook.authorizeCallback(requestCode, resultCode, data);
   }
 }
  /**
   * This function does the heavy lifting of publishing an install.
   *
   * @param fb
   * @param applicationId
   * @param context
   * @throws Exception
   */
  private static void publishInstall(
      final Facebook fb, final String applicationId, final Context context)
      throws JSONException, FacebookError, MalformedURLException, IOException {

    String attributionId = Facebook.getAttributionId(context.getContentResolver());
    SharedPreferences preferences =
        context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE);
    String pingKey = applicationId + "ping";
    long lastPing = preferences.getLong(pingKey, 0);
    if (lastPing == 0 && attributionId != null) {
      Bundle supportsAttributionParams = new Bundle();
      supportsAttributionParams.putString(APPLICATION_FIELDS, SUPPORTS_ATTRIBUTION);
      JSONObject supportResponse =
          Util.parseJson(fb.request(applicationId, supportsAttributionParams));
      Object doesSupportAttribution = (Boolean) supportResponse.get(SUPPORTS_ATTRIBUTION);

      if (!(doesSupportAttribution instanceof Boolean)) {
        throw new JSONException(
            String.format(
                "%s contains %s instead of a Boolean",
                SUPPORTS_ATTRIBUTION, doesSupportAttribution));
      }

      if ((Boolean) doesSupportAttribution) {
        Bundle publishParams = new Bundle();
        publishParams.putString(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT);
        publishParams.putString(ATTRIBUTION_KEY, attributionId);

        String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId);

        fb.request(publishUrl, publishParams, "POST");

        // denote success since no error threw from the post.
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(pingKey, System.currentTimeMillis());
        editor.commit();
      }
    }
  }
Esempio n. 29
0
  private void loginToFacebook() {
    String access_token = gigPrefs.getString("access_token", null);
    long expires = gigPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
      facebook.authorize(
          this,
          new String[] {
            "publish_checkins", "publish_stream",
          },
          new DialogListener() {
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = gigPrefs.edit();
              editor.putString("access_token", facebook.getAccessToken());
              editor.putLong("access_expires", facebook.getAccessExpires());
              editor.commit();
            }

            public void onFacebookError(FacebookError error) {
              Log.i(GigFacebookLogin.class.getName() + " Error", error.toString());
            }

            public void onError(DialogError e) {
              Log.i(GigFacebookLogin.class.getName() + " Error", e.toString());
            }

            public void onCancel() {
              Log.i(GigFacebookLogin.class.getName() + " Cancel", "canceled...");
            }
          });
    }
  }
Esempio n. 30
0
  public void chamarFacebook() {
    // Carrega a accessToken pra saber se o usuário
    // já se autenticou.
    loadAccessToken();

    if (!facebook.isSessionValid()) {

      facebook.authorize(
          this,
          PERMISSIONS,
          new LoginDialogListener() {

            @Override
            public void onComplete(Bundle values) {
              // TODO Auto-generated method stub
              saveAccessToken();
              // getProfileInformation();
            }

            @Override
            public void onFacebookError(FacebookError e) {
              // TODO Auto-generated method stub

            }

            @Override
            public void onError(DialogError e) {
              // TODO Auto-generated method stub

            }

            @Override
            public void onCancel() {
              // TODO Auto-generated method stub

            }
          });
    }
  }