com.facebook.FacebookSdk Java Examples

The following examples show how to use com.facebook.FacebookSdk. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Login.java    From UberClone with MIT License 7 votes vote down vote up
private void setupFacebookStuff() {

        // This should normally be on your application class
        FacebookSdk.sdkInitialize(getApplicationContext());

        mLoginManager = LoginManager.getInstance();
        mFacebookCallbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                //login
                firebaseHelper.registerByFacebookAccount();
            }

            @Override
            public void onCancel() {
                Toast.makeText(Login.this,"The login was canceled",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(Login.this,"There was an error in the login",Toast.LENGTH_SHORT).show();
            }
        });
    }
 
Example #2
Source File: MessengerUtils.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static void shareToMessenger20150314(
    Activity activity,
    int requestCode,
    ShareToMessengerParams shareToMessengerParams) {
  try {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.setPackage(PACKAGE_NAME);
    shareIntent.putExtra(Intent.EXTRA_STREAM, shareToMessengerParams.uri);
    shareIntent.setType(shareToMessengerParams.mimeType);
    String appId = FacebookSdk.getApplicationId();
    if (appId != null) {
      shareIntent.putExtra(EXTRA_PROTOCOL_VERSION, PROTOCOL_VERSION_20150314);
      shareIntent.putExtra(EXTRA_APP_ID, appId);
      shareIntent.putExtra(EXTRA_METADATA, shareToMessengerParams.metaData);
      shareIntent.putExtra(EXTRA_EXTERNAL_URI, shareToMessengerParams.externalUri);
    }

    activity.startActivityForResult(shareIntent, requestCode);
  } catch (ActivityNotFoundException e) {
    Intent openMessenger = activity.getPackageManager().getLaunchIntentForPackage(PACKAGE_NAME);
    activity.startActivity(openMessenger);
  }
}
 
Example #3
Source File: Login.java    From UberClone with MIT License 6 votes vote down vote up
private void setupFacebookStuff() {

        // This should normally be on your application class
        FacebookSdk.sdkInitialize(getApplicationContext());

        mLoginManager = LoginManager.getInstance();
        mFacebookCallbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                //login
                firebaseHelper.registerByFacebookAccount();
            }

            @Override
            public void onCancel() {
                Toast.makeText(Login.this,"The login was canceled",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(Login.this,"There was an error in the login",Toast.LENGTH_SHORT).show();
            }
        });
    }
 
Example #4
Source File: SaudeApp.java    From Saude-no-Mapa with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Fabric.with(this, new Crashlytics());

    Timber.plant(new Timber.DebugTree());

    RealmConfiguration configuration = new RealmConfiguration.Builder(this)
            .deleteRealmIfMigrationNeeded()
            .build();

    Realm.setDefaultConfiguration(configuration);

    FacebookSdk.sdkInitialize(getApplicationContext());
    Timber.i("Signature " +  FacebookSdk.getApplicationSignature(getApplicationContext()));
}
 
Example #5
Source File: UpodsApplication.java    From uPods-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    isLoaded = false;
    applicationContext = getApplicationContext();
    YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY);
    YandexMetrica.enableActivityAutoTracking(this);
    FacebookSdk.sdkInitialize(applicationContext);
    LoginMaster.getInstance().init();
    new Prefs.Builder()
            .setContext(this)
            .setMode(ContextWrapper.MODE_PRIVATE)
            .setPrefsName(getPackageName())
            .setUseDefaultSharedPreference(true).build();

    super.onCreate();
}
 
Example #6
Source File: FirstLaunchAnalytics.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public Completable sendAppStart(android.app.Application application,
    SharedPreferences sharedPreferences, IdsRepository idsRepository) {

  FacebookSdk.sdkInitialize(application);
  AppEventsLogger.activateApp(application);
  AppEventsLogger.newLogger(application);
  return idsRepository.getUniqueIdentifier()
      .doOnSuccess(AppEventsLogger::setUserID)
      .toObservable()
      .doOnNext(__ -> setupRakamFirstLaunchSuperProperty(
          SecurePreferences.isFirstRun(sharedPreferences)))
      .doOnNext(__ -> sendPlayProtectEvent())
      .doOnNext(__ -> setupDimensions(application))
      .filter(__ -> SecurePreferences.isFirstRun(sharedPreferences))
      .doOnNext(
          __ -> sendFirstLaunchEvent(utmSource, utmMedium, utmCampaign, utmContent, entryPoint))
      .toCompletable()
      .subscribeOn(Schedulers.io());
}
 
Example #7
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private void initialize()
        throws FileNotFoundException {
    ParcelFileDescriptor fileDescriptor = null;
    try {
        if (Utility.isFileUri(videoUri)) {
            fileDescriptor = ParcelFileDescriptor.open(
                    new File(videoUri.getPath()),
                    ParcelFileDescriptor.MODE_READ_ONLY);
            videoSize = fileDescriptor.getStatSize();
            videoStream = new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor);
        } else if (Utility.isContentUri(videoUri)) {
            videoSize = Utility.getContentSize(videoUri);
            videoStream = FacebookSdk
                    .getApplicationContext()
                    .getContentResolver()
                    .openInputStream(videoUri);
        } else {
            throw new FacebookException("Uri must be a content:// or file:// uri");
        }
    } catch (FileNotFoundException e) {
        Utility.closeQuietly(videoStream);

        throw e;
    }
}
 
Example #8
Source File: ApplicationModule.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Singleton @Provides AptoideAccountManager provideAptoideAccountManager(AdultContent adultContent,
    GoogleApiClient googleApiClient, StoreManager storeManager, AccountService accountService,
    LoginPreferences loginPreferences, AccountPersistence accountPersistence,
    @Named("facebookLoginPermissions") List<String> facebookPermissions) {
  FacebookSdk.sdkInitialize(application);

  return new AptoideAccountManager.Builder().setAccountPersistence(
      new MatureContentPersistence(accountPersistence, adultContent))
      .setAccountService(accountService)
      .setAdultService(adultContent)
      .registerSignUpAdapter(GoogleSignUpAdapter.TYPE,
          new GoogleSignUpAdapter(googleApiClient, loginPreferences))
      .registerSignUpAdapter(FacebookSignUpAdapter.TYPE,
          new FacebookSignUpAdapter(facebookPermissions, LoginManager.getInstance(),
              loginPreferences))
      .setStoreManager(storeManager)
      .build();
}
 
Example #9
Source File: MyApp.java    From FaceT with Mozilla Public License 2.0 6 votes vote down vote up
@Override
    public void onCreate() {
        super.onCreate();
        Log.d("Myapp " , " start");
//        _instance = this;
        FirebaseApp.getApps(this);
        //enable the offline capability for firebase
        if (!FirebaseApp.getApps(this).isEmpty()) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }

        EmojiManager.install(new EmojiOneProvider());
        Picasso.Builder builder = new Picasso.Builder(this);
//        builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
        Picasso built = builder.build();
//        built.setIndicatorsEnabled(false);
//        built.setLoggingEnabled(true);
        Picasso.setSingletonInstance(built);

        // Initialize the SDK before executing any other operations,
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
 
Example #10
Source File: NativeProtocol.java    From letv with Apache License 2.0 6 votes vote down vote up
private static TreeSet<Integer> fetchAllAvailableProtocolVersionsForAppInfo(NativeAppInfo appInfo) {
    TreeSet<Integer> allAvailableVersions = new TreeSet();
    ContentResolver contentResolver = FacebookSdk.getApplicationContext().getContentResolver();
    String[] projection = new String[]{"version"};
    Uri uri = buildPlatformProviderVersionURI(appInfo);
    Cursor c = null;
    try {
        if (FacebookSdk.getApplicationContext().getPackageManager().resolveContentProvider(appInfo.getPackage() + PLATFORM_PROVIDER, 0) != null) {
            c = contentResolver.query(uri, projection, null, null, null);
            if (c != null) {
                while (c.moveToNext()) {
                    allAvailableVersions.add(Integer.valueOf(c.getInt(c.getColumnIndex("version"))));
                }
            }
        }
        if (c != null) {
            c.close();
        }
        return allAvailableVersions;
    } catch (Throwable th) {
        if (c != null) {
            c.close();
        }
    }
}
 
Example #11
Source File: AppLinkData.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
/**
 * Asynchronously fetches app link information that might have been stored for use after
 * installation of the app
 *
 * @param context           The context
 * @param applicationId     Facebook application Id. If null, it is taken from the manifest
 * @param completionHandler CompletionHandler to be notified with the AppLinkData object or null
 *                          if none is available.  Must not be null.
 */
public static void fetchDeferredAppLinkData(
        Context context,
        String applicationId,
        final CompletionHandler completionHandler) {
    Validate.notNull(context, "context");
    Validate.notNull(completionHandler, "completionHandler");

    if (applicationId == null) {
        applicationId = Utility.getMetadataApplicationId(context);
    }

    Validate.notNull(applicationId, "applicationId");

    final Context applicationContext = context.getApplicationContext();
    final String applicationIdCopy = applicationId;
    FacebookSdk.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            fetchDeferredAppLinkFromServer(
                    applicationContext, applicationIdCopy, completionHandler);
        }
    });
}
 
Example #12
Source File: DialogPresenter.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static void setupAppCallForErrorResult(AppCall appCall, FacebookException exception) {
    if (exception == null) {
        return;
    }
    Validate.hasFacebookActivity(FacebookSdk.getApplicationContext());

    Intent errorResultIntent = new Intent();
    errorResultIntent.setClass(FacebookSdk.getApplicationContext(), FacebookActivity.class);
    errorResultIntent.setAction(FacebookActivity.PASS_THROUGH_CANCEL_ACTION);

    NativeProtocol.setupProtocolRequestIntent(
            errorResultIntent,
            appCall.getCallId().toString(),
            null,
            NativeProtocol.getLatestKnownVersion(),
            NativeProtocol.createBundleForException(exception));

    appCall.setRequestIntent(errorResultIntent);
}
 
Example #13
Source File: DialogPresenter.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static void setupAppCallForWebDialog(
        AppCall appCall,
        String actionName,
        Bundle parameters) {
    Validate.hasFacebookActivity(FacebookSdk.getApplicationContext());
    Validate.hasInternetPermissions(FacebookSdk.getApplicationContext());

    Bundle intentParameters = new Bundle();
    intentParameters.putString(NativeProtocol.WEB_DIALOG_ACTION, actionName);
    intentParameters.putBundle(NativeProtocol.WEB_DIALOG_PARAMS, parameters);

    Intent webDialogIntent = new Intent();
    NativeProtocol.setupProtocolRequestIntent(
            webDialogIntent,
            appCall.getCallId().toString(),
            actionName,
            NativeProtocol.getLatestKnownVersion(),
            intentParameters);
    webDialogIntent.setClass(FacebookSdk.getApplicationContext(), FacebookActivity.class);
    webDialogIntent.setAction(FacebookDialogFragment.TAG);

    appCall.setRequestIntent(webDialogIntent);
}
 
Example #14
Source File: FacebookDialogBase.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
protected void showImpl(final CONTENT content, final Object mode) {
    AppCall appCall = createAppCallForMode(content, mode);
    if (appCall != null) {
        if (fragment != null) {
            DialogPresenter.present(appCall, fragment);
        } else {
            DialogPresenter.present(appCall, activity);
        }
    } else {
        // If we got a null appCall, then the derived dialog code is doing something wrong
        String errorMessage = "No code path should ever result in a null appCall";
        Log.e(TAG, errorMessage);
        if (FacebookSdk.isDebugEnabled()) {
            throw new IllegalStateException(errorMessage);
        }
    }
}
 
Example #15
Source File: NativeProtocol.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static void updateAllAvailableProtocolVersionsAsync() {
    if (!protocolVersionsAsyncUpdating.compareAndSet(false, true)) {
        return;
    }

    FacebookSdk.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            try {
                for (NativeAppInfo appInfo : facebookAppInfoList) {
                    appInfo.fetchAvailableVersions(true);
                }
            } finally {
                protocolVersionsAsyncUpdating.set(false);
            }
        }
    });
}
 
Example #16
Source File: Utility.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static long getContentSize(final Uri contentUri) {
    Cursor cursor = null;
    try {
        cursor = FacebookSdk
                .getApplicationContext()
                .getContentResolver()
                .query(contentUri, null, null, null, null);
        int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);

        cursor.moveToFirst();
        return cursor.getLong(sizeIndex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
 
Example #17
Source File: NativeAppCallAttachmentStore.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static void processAttachmentFile(
        Uri imageUri,
        boolean isContentUri,
        File outputFile) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    try {
        InputStream inputStream = null;
        if (!isContentUri) {
            inputStream = new FileInputStream(imageUri.getPath());
        } else {
            inputStream = FacebookSdk
                    .getApplicationContext()
                    .getContentResolver()
                    .openInputStream(imageUri);
        }

        Utility.copyAndCloseInputStream(inputStream, outputStream);
    } finally {
        Utility.closeQuietly(outputStream);
    }
}
 
Example #18
Source File: AppEventsLogger.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
 * Notifies the events system that the app has launched & logs an activatedApp event.  Should be
 * called whenever your app becomes active, typically in the onResume() method of each
 * long-running Activity of your app.
 *
 * @param context       Used to access the attributionId for non-authenticated users.
 * @param applicationId The specific applicationId to report the activation for.
 */
public static void activateApp(Context context, String applicationId) {
    if (context == null || applicationId == null) {
        throw new IllegalArgumentException("Both context and applicationId must be non-null");
    }

    if ((context instanceof Activity)) {
        setSourceApplication((Activity) context);
    } else {
      // If context is not an Activity, we cannot get intent nor calling activity.
      resetSourceApplication();
      Log.d(AppEventsLogger.class.getName(),
          "To set source application the context of activateApp must be an instance of" +
                  " Activity");
    }

    // activateApp supersedes publishInstall in the public API, so we need to explicitly invoke
    // it, since the server can't reliably infer install state for all conditions of an app
    // activate.
    FacebookSdk.publishInstallAsync(context, applicationId);

    final AppEventsLogger logger = new AppEventsLogger(context, applicationId, null);
    final long eventTime = System.currentTimeMillis();
    final String sourceApplicationInfo = getSourceApplication();
    backgroundExecutor.execute(new Runnable() {
        @Override
        public void run() {
            logger.logAppSessionResumeEvent(eventTime, sourceApplicationInfo);
        }
    });
}
 
Example #19
Source File: FBLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
public FBLoginInstance(Activity activity, final LoginListener listener,
                       final boolean fetchUserInfo) {
    super(activity, listener, fetchUserInfo);
    if (!FacebookSdk.isInitialized()) {
        FacebookSdk.setApplicationId(ShareManager.CONFIG.getFbClientId());
        FacebookSdk.sdkInitialize(activity.getApplicationContext());
        if (BuildConfig.DEBUG) {
            FacebookSdk.setIsDebugEnabled(true);
            FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        }
    }

    callbackManager = CallbackManager.Factory.create();
}
 
Example #20
Source File: AppEventsLogger.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static void flush(final FlushReason reason) {

        FacebookSdk.getExecutor().execute(new Runnable() {
            @Override
            public void run() {
                flushAndWait(reason);
            }
        });
    }
 
Example #21
Source File: LoginActivity.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    initGoogleSignIn();
    initFirebaseAuth();
    initFacebookSignIn();
}
 
Example #22
Source File: LoginActivity.java    From Simple-Blog-App with MIT License 5 votes vote down vote up
private void fbInit() {

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d("facebook:token", AccessToken.getCurrentAccessToken().getToken());
                AccessToken.getCurrentAccessToken().getToken();
                signInWithFacebook(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });
        fbImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "user_location", "user_birthday", "public_profile", "user_friends"));
            }
        });
    }
 
Example #23
Source File: AppEventsLogger.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static void logEvent(final Context context,
                             final AppEvent event,
                             final AccessTokenAppIdPair accessTokenAppId) {
    FacebookSdk.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            SessionEventsState state = getSessionEventsState(context, accessTokenAppId);
            state.addEvent(event);
            flushIfNecessary();
        }
    });
}
 
Example #24
Source File: FacebookDialogBase.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
* Set the request code for the startActivityForResult call. The requestCode should be
* outside of the range of those reserved for the Facebook SDK
* {@link com.facebook.FacebookSdk#isFacebookRequestCode(int)}.
*
* @param requestCode the request code to use.
*/
protected void setRequestCode(int requestCode) {
    if (FacebookSdk.isFacebookRequestCode(requestCode)) {
        throw new IllegalArgumentException("Request code " + requestCode +
                " cannot be within the range reserved by the Facebook SDK.");
    }
    this.requestCode = requestCode;
}
 
Example #25
Source File: PermissionServiceActivity.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  sharedPreferences =
      ((AptoideApplication) getApplicationContext()).getDefaultSharedPreferences();
  if (!FacebookSdk.isInitialized()) {
    FacebookSdk.sdkInitialize(getApplicationContext());
  }
}
 
Example #26
Source File: App.java    From ONE-Unofficial with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Paper.init(this);

    CrashHandler.getInstance().init(this);
    ImageUtil.init(this);
    NetworkUtil.init(this);
    ConfigUtil.init(this);
    TextToast.init(this);

    //Facebook分享初始化
    FacebookSdk.sdkInitialize(getApplicationContext());
    //友盟意见反馈初始化
    FeedbackPush.getInstance(this).init(false);
}
 
Example #27
Source File: LockOnGetVariable.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
public LockOnGetVariable(final Callable<T> callable) {
    initLatch = new CountDownLatch(1);
    FacebookSdk.getExecutor().execute(
            new FutureTask<>(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        LockOnGetVariable.this.value = callable.call();
                    } finally {
                        initLatch.countDown();
                    }
                    return null;
                }
            }));
}
 
Example #28
Source File: NativeAppCallAttachmentStore.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private Attachment(UUID callId, Bitmap bitmap, Uri uri) {
    this.callId = callId;
    this.bitmap = bitmap;
    this.originalUri = uri;

    if (uri != null) {
        String scheme = uri.getScheme();
        if ("content".equalsIgnoreCase(scheme)) {
            isContentUri = true;
            shouldCreateFile = uri.getAuthority() != null &&
                    !uri.getAuthority().startsWith("media");
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            shouldCreateFile = true;
        } else if (!Utility.isWebUri(uri)) {
            throw new FacebookException("Unsupported scheme for media Uri : " + scheme);
        }
    } else if (bitmap != null) {
        shouldCreateFile = true;
    } else {
        throw new FacebookException("Cannot share media without a bitmap or Uri set");
    }

    attachmentName = !shouldCreateFile ? null : UUID.randomUUID().toString();
    attachmentUrl = !shouldCreateFile
            ? this.originalUri.toString()
            : FacebookContentProvider.getAttachmentUrl(
                    FacebookSdk.getApplicationId(),
                    callId,
                    attachmentName);
}
 
Example #29
Source File: NativeAppCallAttachmentStore.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
synchronized static File getAttachmentsDirectory() {
    if (attachmentsDirectory == null) {
        attachmentsDirectory = new File(
                FacebookSdk.getApplicationContext().getCacheDir(),
                ATTACHMENTS_DIR_NAME);
    }
    return attachmentsDirectory;
}
 
Example #30
Source File: Validate.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
public static String hasAppID() {
    String id = FacebookSdk.getApplicationId();
    if (id == null) {
        throw new IllegalStateException("No App ID found, please set the App ID.");
    }
    return id;
}