public void initialize(LoginButton fbLoginBtn, CallbackManager callbackManager) {

    // Setting permissions for fetching facebook content and performing facebook actions (eg:
    // posting on facebook)
    List<String> facebookPermissions =
        Arrays.asList(
            "user_photos", "email", "user_birthday", "user_friends", "read_custom_friendlists");
    fbLoginBtn.setReadPermissions(facebookPermissions);

    // Callback registration
    fbLoginBtn.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();
          }

          @Override
          public void onCancel() {
            Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
          }

          @Override
          public void onError(FacebookException exception) {
            Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
          }
        });
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this);
    setContentView(R.layout.activity_log_in);

    // setViewObject();
    // setListner();

    callbackManager = CallbackManager.Factory.create();
    // LoginButtonはFacebookSDKに含まれたButtonウィジェットの拡張ウィジェット。
    loginButton = (LoginButton) findViewById(R.id.login_btn_facebook);
    // APIから取得したいユーザー情報の種類を指定し、パーミッションを許可する。
    List<String> permissionNeeds =
        Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
    loginButton.setReadPermissions(permissionNeeds);

    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            System.out.println("");
            GraphRequest request =
                GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                      @Override
                      public void onCompleted(JSONObject object, GraphResponse response) {
                        // API連携に成功し、ログイン状態になったら、下記のようなゲッター関数により、ユーザー情報を取得することが出来る。
                        try {
                          String id = object.getString("id");
                          String name = object.getString("name");
                          String email = object.getString("email");
                          String gender = object.getString("gender");
                          String birthday = object.getString("birthday");
                          System.out.println(name);
                        } catch (JSONException e) {
                          e.printStackTrace();
                        }
                      }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();
          }

          @Override
          public void onCancel() {
            System.out.println("onCancel");
          }

          @Override
          public void onError(FacebookException exception) {
            Log.v("LoginActivity", exception.toString());
          }
        });
  }
Ejemplo n.º 3
0
 @Override
 public void onViewCreated(View view, Bundle savedInstanceState) {
   super.onViewCreated(view, savedInstanceState);
   LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
   loginButton.setReadPermissions("user_friends");
   loginButton.setFragment(this);
   loginButton.registerCallback(mCallbackManager, mCallback);
 }
  public void signInWithFaceButton(LoginButton loginButton) {
    List<String> permissionNeeds = Arrays.asList("email", "user_about_me");
    loginButton.setReadPermissions(permissionNeeds);
    loginButton.registerCallback(
        mCallbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {

            GraphRequest request =
                GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                      @Override
                      public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.v("TAG", "JSON: " + object);
                        try {
                          String id = object.getString("id");
                          String foto =
                              "https://graph.facebook.com/" + id + "/picture?height=120&width=120";
                          String nome = object.getString("name");
                          String email = object.getString("email");
                          if (mFaceCallback != null) {
                            mFaceCallback.getInfoFace(id, nome, email, foto);
                          } else {
                            throw new IllegalArgumentException(
                                "interface InfoLoginFaceCallback is null");
                          }
                        } catch (JSONException e) {
                          e.printStackTrace();
                        }
                      }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,picture.width(120).height(120)");
            request.setParameters(parameters);
            request.executeAsync();
          }

          @Override
          public void onCancel() {
            if (mFaceCallback != null) {
              mFaceCallback.cancelLoginFace();
            } else {
              throw new IllegalArgumentException("interface InfoLoginFaceCallback is null");
            }
          }

          @Override
          public void onError(FacebookException error) {
            if (mFaceCallback != null) {
              mFaceCallback.erroLoginFace(error);
            } else {
              throw new IllegalArgumentException("interface InfoLoginFaceCallback is null");
            }
          }
        });
  }
Ejemplo n.º 5
0
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    btnConnectWithFacebook = (LoginButton) getActivity().findViewById(R.id.btnConnectWithFacebok);
    btnConnectWithFacebook.setTypeface(
        FontManager.setFont(getActivity(), FontManager.Font.OpenSansSemiBold));

    btnConnectWithFacebook.setReadPermissions(Arrays.asList("public_profile, email"));
    btnConnectWithFacebook.setFragment(this);
    btnConnectWithFacebook.registerCallback(callbackManager, callback);
  }
  @Test
  public void testCantSetPublishThenReadPermissions() throws Exception {
    Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();

    LoginButton loginButton = (LoginButton) activity.findViewById(R.id.login_button);
    loginButton.setPublishPermissions("publish_actions");
    try {
      loginButton.setReadPermissions("user_location");
    } catch (UnsupportedOperationException e) {
      return;
    }
    fail();
  }
Ejemplo n.º 7
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.facebook_login);
    // Initialise facebook SDK
    FacebookSdk.sdkInitialize(getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();

    mCircularImageView = (CircularImageView) findViewById(R.id.imageView);
    txtName = (TextView) findViewById(R.id.txt_name);
    //        txtDOB = (TextView) findViewById(R.id.txt_dob);
    txtName.setText("this is sample text");
    mLoginButton = (LoginButton) findViewById(R.id.login_button);
    mLoginButton.setReadPermissions("user_friends");

    LoginManager.getInstance()
        .registerCallback(
            mCallbackManager,
            new FacebookCallback<LoginResult>() {
              @Override
              public void onSuccess(LoginResult loginResult) {
                updateUI();
              }

              @Override
              public void onCancel() {
                Log.v(logString, "Login cancle");
              }

              @Override
              public void onError(FacebookException error) {

                Log.e(logString, "error");
                error.printStackTrace();
              }
            });

    profileTracker =
        new ProfileTracker() {
          @Override
          protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
            Log.v(logString, "onCurrentProfileTracker");
            updateUI();
          }
        };

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
  }
Ejemplo n.º 8
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // initializing facebook sdk
    FacebookSdk.sdkInitialize(getApplicationContext());

    // setting layout
    setContentView(R.layout.activity_login);

    // binding id's to view
    ButterKnife.bind(this);

    // facebook login button
    fbLoginButton.setReadPermissions("user_friends", "public_profile");

    // initializing callback function
    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    fbLoginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            // App code
            //                getUserDetail();
            //                Intent goToNavigation = new Intent(LoginActivity.this,
            // NavigationDrawerActivity.class);
          }

          @Override
          public void onCancel() {
            Snackbar.make(
                    fbLoginButton,
                    "Can not login using Facebook, Please try logging again or Enter application without logging in",
                    Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();
          }

          @Override
          public void onError(FacebookException exception) {
            Snackbar.make(fbLoginButton, "Some Error occurred! Login again", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();
          }
        });
  }
Ejemplo n.º 9
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
    mClient.connect();

    Intent sIntent = new Intent(this, BeeplePaperService.class);
    startService(sIntent);

    FacebookSdk.sdkInitialize(getApplicationContext());

    setContentView(R.layout.activity_main);

    final Button btn = (Button) findViewById(R.id.mButt);

    btn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent mIntent = new Intent(Intent.ACTION_SEND);
            sendBroadcast(mIntent);
          }
        });

    callbackManager = CallbackManager.Factory.create();
    Log.d(TAG, "Building login button for FB");
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "Getting access token");
          }

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

          @Override
          public void onError(FacebookException exception) {
            Log.e(TAG, exception.toString());
          }
        });
  }
Ejemplo n.º 10
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);

    callbackManager = CallbackManager.Factory.create();
    googleApiClient =
        new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .build();

    LoginButton loginButton = (LoginButton) findViewById(R.id.activity_login_facebook);
    googleSignIn = (SignInButton) findViewById(R.id.activity_login_google);
    getToken = (Button) findViewById(R.id.activity_login_auth_token);

    loginButton.setReadPermissions("email");

    facebookTokenTracker =
        new AccessTokenTracker() {
          @Override
          protected void onCurrentAccessTokenChanged(
              AccessToken oldAccessToken, AccessToken newAccessToken) {
            isFbLogin = true;
            Toast.makeText(LoginActivity.this, "Facebook Access Token", Toast.LENGTH_SHORT).show();
          }
        };

    facebookProfileTracker =
        new ProfileTracker() {
          @Override
          protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
            isFbLogin = (!isFbLogin);
            Toast.makeText(LoginActivity.this, "Facebook Current Profile", Toast.LENGTH_SHORT)
                .show();
          }
        };

    facebookTokenTracker.startTracking();
    facebookProfileTracker.startTracking();
    googleSignIn.setOnClickListener(this);
    getToken.setOnClickListener(this);
  }
Ejemplo n.º 11
0
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginButton = (LoginButton) view.findViewById(R.id.ivfb);
    tvUser = (TextView) getView().findViewById(R.id.tvUser);
    etEmail = (EditText) getView().findViewById(R.id.etEmail);
    etUser = (EditText) getView().findViewById(R.id.etUser);
    etPhone = (EditText) getView().findViewById(R.id.etPhone);
    etPass = (EditText) getView().findViewById(R.id.etPass);
    bLogin = (Button) view.findViewById(R.id.bLogin);
    bReg = (Button) view.findViewById(R.id.bReg);
    ivgp = (ImageView) view.findViewById(R.id.ivgp);

    loginButton.setReadPermissions("user_friends");
    loginButton.setFragment(this);
    loginButton.registerCallback(callbackManager, callback);
  }
Ejemplo n.º 12
0
  @Test
  public void testLoginButtonWithReadPermissions() throws Exception {
    LoginManager loginManager = mock(LoginManager.class);
    Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();

    LoginButton loginButton = (LoginButton) activity.findViewById(R.id.login_button);
    ArrayList<String> permissions = new ArrayList<>();
    permissions.add("user_location");
    loginButton.setReadPermissions(permissions);
    loginButton.setDefaultAudience(DefaultAudience.EVERYONE);
    loginButton.setLoginManager(loginManager);
    loginButton.performClick();

    verify(loginManager).logInWithReadPermissions(activity, permissions);
    verify(loginManager, never()).logInWithPublishPermissions(isA(Activity.class), anyCollection());
    // Verify default audience is channeled
    verify(loginManager).setDefaultAudience(DefaultAudience.EVERYONE);
  }
Ejemplo n.º 13
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);
    callbackManager = CallbackManager.Factory.create();

    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile");

    // Callback registration
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            updateDatabase();
            // jump to another activity
            Intent showPosts = new Intent(LoginActivity.this, PostActivity.class);
            startActivity(showPosts);
          }

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

          @Override
          public void onError(FacebookException exception) {
            showAlert();
          }

          private void showAlert() {
            new AlertDialog.Builder(LoginActivity.this)
                .setTitle(R.string.cancelled)
                .setMessage(R.string.login_failed)
                .setPositiveButton(R.string.ok, null)
                .show();
          }
        });

    LoginManager.getInstance()
        .logInWithReadPermissions(this, Collections.singletonList("public_profile"));
  }
Ejemplo n.º 14
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());

    setContentView(R.layout.activity_main);

    callbackManager = CallbackManager.Factory.create();

    final LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile", "email", "user_friends");

    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {

          @Override
          public void onSuccess(LoginResult loginResult) {

            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
            startActivity(intent);

            System.out.print("Logged in");
          }

          @Override
          public void onCancel() {
            // App code
          }

          @Override
          public void onError(FacebookException exception) {
            Toast.makeText(
                    MainActivity.this, "Error al realizar Login Facebook", Toast.LENGTH_SHORT)
                .show();
            Log.i("Error", "Error");
          }
        });

    // printHashKey();

  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);

    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    loginButton.setFragment(this);
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Toast.makeText(getActivity(), "Login successful", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onCancel() {
            Toast.makeText(getActivity(), "Login canceled", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onError(FacebookException exception) {
            Toast.makeText(getActivity(), "Login error", Toast.LENGTH_SHORT).show();
          }
        });

    skipLoginButton = (TextView) view.findViewById(R.id.skip_login_button);
    skipLoginButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            if (skipLoginCallback != null) {
              skipLoginCallback.onSkipLoginPressed();
            }
          }
        });

    return view;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signin);
    getComponent().inject(this);
    ButterKnife.bind(this);
    loginButton.setReadPermissions("email");

    callbackManager = CallbackManager.Factory.create();

    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "Successfully signed in with facebook!");
            Services.weClimbService()
                .getAccessToken(loginResult.getAccessToken().getToken())
                .enqueue(
                    new Callback<WcrAccessToken>() {

                      @Override
                      public void onResponse(
                          Call<WcrAccessToken> call, Response<WcrAccessToken> response) {
                        if (response.isSuccessful()) {
                          WcrAccessToken token = response.body();
                          Log.i(TAG, "Successfully got WcrAccessToken from server: " + token);
                          preferencesService.putAccessToken(token);
                        } else {
                          try {
                            Log.i(
                                TAG,
                                "Failed to get access token: " + response.errorBody().string());
                          } catch (IOException e) {
                            e.printStackTrace();
                          }
                        }
                      }

                      @Override
                      public void onFailure(Call<WcrAccessToken> call, Throwable t) {
                        Snackbar.make(loginButton, R.string.error_generic, LENGTH_SHORT).show();
                        Log.e(TAG, "Error geting access token", t);
                      }
                    });
          }

          @Override
          public void onCancel() {
            Log.d(TAG, "Facebook sign in cancelled!");
          }

          @Override
          public void onError(FacebookException exception) {
            Log.d(TAG, "Facebook sign in error!");
          }
        });

    new AccessTokenTracker() {
      @Override
      protected void onCurrentAccessTokenChanged(
          AccessToken oldAccessToken, AccessToken currentAccessToken) {
        if (currentAccessToken == null) {
          preferencesService.removeAccessToken();
        }
      }
    };
  }
Ejemplo n.º 17
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // initialize our instance of CallbackManager
    callbackManager = CallbackManager.Factory.create();

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_one, container, false);

    logo = (ImageView) view.findViewById(R.id.conveneLogo);
    logo.bringToFront();

    userName = (TextView) view.findViewById(R.id.userName);
    btnSyncContacts = (Button) view.findViewById(R.id.btnSearchContacts);
    info = (TextView) view.findViewById(R.id.info);
    orText = (TextView) view.findViewById(R.id.ortext);
    profileImage = (ImageView) view.findViewById(R.id.profileimage);
    backButtons = (LinearLayout) view.findViewById(R.id.backButtonsContainer);
    loginButton = (LoginButton) view.findViewById(R.id.login_button);
    lvFriend = (ListView) view.findViewById(R.id.lvFriend);
    userInfo = (RelativeLayout) view.findViewById(R.id.fbInfoContainer);

    // get user permission to access to friends list
    loginButton.setReadPermissions(Arrays.asList("user_friends"));
    loginButton.setFragment(this);

    // create a callback to handle the results of the login attempts and
    // register it with the CallbackManager
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.d("FragmentOne.FBLOGIN", "Login attempt a success!!.");
          }

          @Override
          public void onCancel() {
            Log.d("FragmentOne.FBLOGIN", "Login attempt cancelled.");
          }

          @Override
          public void onError(FacebookException e) {
            Log.d("FragmentOne.FBLOGIN", "Login attempt failed.");
          }
        });

    friendListArray.clear();
    // NOTE: simple list item 1 = Android predefined TextView resource id
    // adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,
    // friendListArray);

    newadapter = new myAdapter(getContext(), R.layout.list_row, friendListArray);

    lvFriend.setAdapter(newadapter);

    lvFriend.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int friendListID = (int) id;
            newadapter.setSelectedIndex(position);
            People person = (People) lvFriend.getItemAtPosition(friendListID);
            utils.setFriend(person.name);
          }
        });

    Profile profile = Profile.getCurrentProfile();
    if (profile == null) {
      //
    } else {
      FbProfileInfo FBInfo = new FbProfileInfo(getActivity());
      FBInfo.getProfileInformation(getActivity());
      setUpFriendListPage();
    }

    return view;
  }
Ejemplo n.º 18
0
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    login = (Button) findViewById(R.id.login_button_amhungry);
    mTokenTracker =
        new AccessTokenTracker() {
          @Override
          protected void onCurrentAccessTokenChanged(
              AccessToken oldAccessToken, AccessToken currentAccessToken) {}
        };
    mProfileTracker =
        new ProfileTracker() {
          @Override
          protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
            displayWelcomeMessage(currentProfile);
          }
        };
    mTokenTracker.startTracking();
    mProfileTracker.startTracking();

    login.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);

            finish();
          }
        });

    mCallback =
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();

            //                mTextDetails.setText("user " + accessToken.getUserId());
            Profile profile = Profile.getCurrentProfile();
            displayWelcomeMessage(profile);
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);

            startActivity(intent);

            finish();
          }

          @Override
          public void onCancel() {
            Log.d("profile_me", "hhhhhh");
          }

          @Override
          public void onError(FacebookException error) {
            Log.d("profile_me", "hhhhhh");
          }
        };

    callbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button_facebook);
    loginButton.setReadPermissions("public_profile");
    loginButton.registerCallback(callbackManager, mCallback);
  }
Ejemplo n.º 19
0
  public void showSocialLoginDialog() {
    smsPB.setVisibility(View.GONE);
    final MaterialDialog dialog =
        new MaterialDialog.Builder(getActivity())
            .customView(R.layout.smartdialog, false)
            .title("Sign Up")
            .titleGravity(GravityEnum.CENTER)
            .positiveText("SKIP")
            .cancelable(false)
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    super.onPositive(dialog);
                    dialog.dismiss();

                    mixpanel.track("Login - Skipped");
                    Intent mIntent = new Intent(getActivity(), LoginUserDetails.class);
                    startActivity(mIntent);
                  }
                })
            .show();

    View view = dialog.getCustomView();

    callbackManager = CallbackManager.Factory.create();
    LoginButton facebookBtn = (LoginButton) view.findViewById(R.id.smartDialogFacebook);
    facebookBtn.setFragment(this);
    facebookBtn.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
    facebookBtn.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "Facebook login success");
            try {
              getUserFacebookDetails(loginResult);
            } catch (Exception e) {
              Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
          }

          @Override
          public void onCancel() {
            Log.d(TAG, "Facebook login cancel");
          }

          @Override
          public void onError(FacebookException e) {
            Log.d(TAG, "Facebook login error");
            Toast.makeText(
                    getActivity(),
                    "Couldn't login with facebook, try again" + e.getMessage(),
                    Toast.LENGTH_SHORT)
                .show();
          }
        });

    SignInButton googleBtn = (SignInButton) view.findViewById(R.id.smartDialogGoogle);

    googleBtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (mGoogleApiClient.isConnected()) {
              Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
              mGoogleApiClient.disconnect();
            } else {
              mShouldResolve = true;
              mGoogleApiClient.connect();
            }
          }
        });
  }
Ejemplo n.º 20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    isGoogleLogin = false;

    // Facebook Login Code
    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();
    fbLoginButton = (LoginButton) findViewById(R.id.fb_login_button);
    fbLoginButton.setReadPermissions(Arrays.asList("email"));
    fbLoginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            // bug in fb login
            /*
            AccessToken accessToken=loginResult.getAccessToken();
            Profile profile=Profile.getCurrentProfile();
            String userName=profile.getName();
            String userEmail=profile.getId();
            Uri userPhoto=profile.getProfilePictureUri(64,64);
            Preferences.putString(Preferences.USER_NAME,userName);
            Preferences.putString(Preferences.USER_EMAIL,userEmail);
            Preferences.putString(Preferences.USER_PHOTO,userPhoto.toString());
            */
            Toast.makeText(getApplicationContext(), "Successfull Login", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onCancel() {
            Toast.makeText(getApplicationContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onError(FacebookException error) {
            Toast.makeText(getApplicationContext(), "Login Error", Toast.LENGTH_SHORT).show();
          }
        });

    // Google Login Code
    gso =
        new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestProfile()
            .build();
    mGoogleApiClient =
        new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    googleLoginButton = (SignInButton) findViewById(R.id.google_login_button);
    googleLoginButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            googleSignIn();
          }
        });
  }
Ejemplo n.º 21
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    remplaceFont.replaceDefaultFont(this, "DEFAULT", "Exo-Medium.otf");
    remplaceFont.replaceDefaultFont(this, "SANS", "Roboto-Light.ttf");
    remplaceFont.replaceDefaultFont(this, "SERIF", "Roboto-Light.ttf");
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this);
    setContentView(R.layout.activity_inscription);

    firstName = (TextInputLayout) findViewById(R.id.layoutFirstName);
    lastName = (TextInputLayout) findViewById(R.id.layoutLastName);
    email = (TextInputLayout) findViewById(R.id.layoutEmail);
    emailConfirmed = (TextInputLayout) findViewById(R.id.layoutEmailConfirmed);
    password = (TextInputLayout) findViewById(R.id.layoutPassword);
    passwordConfirmed = (TextInputLayout) findViewById(R.id.layoutPasswordConfirmed);
    inscrptionButton = (ImageView) findViewById(R.id.inscrptionButton);

    progressBar = (ProgressBar) findViewById(R.id.ProgressBar);
    imageSuccess = (ImageView) findViewById(R.id.yes);
    imageEchec = (ImageView) findViewById(R.id.no);

    progressBar.setVisibility(View.GONE);
    imageSuccess.setVisibility(View.GONE);
    imageEchec.setVisibility(View.GONE);

    Retrofit retrofit = new Retrofit.Builder().baseUrl(GitHubService.baseUrl).build();

    gitHubService = retrofit.create(GitHubService.class);

    if (Build.VERSION.SDK_INT >= 21) {
      Slide slide = new Slide();
      slide.setDuration(400);
      getWindow().setEnterTransition(slide);
      getWindow()
          .setReturnTransition(
              TransitionInflater.from(this).inflateTransition(R.transition.shared_element_a));
    }

    inscrptionButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            String firstNameValue = firstName.getEditText().getText().toString();
            String lastNameValue = lastName.getEditText().getText().toString();
            String emailValue = email.getEditText().getText().toString();
            String emailConfirmedValue = emailConfirmed.getEditText().getText().toString();
            String passwordValue = password.getEditText().getText().toString();
            String passwordConfirmedValue = passwordConfirmed.getEditText().getText().toString();

            firstName.setErrorEnabled(false);
            firstName.requestFocus();
            lastName.setErrorEnabled(false);
            lastName.requestFocus();
            email.setErrorEnabled(false);
            email.requestFocus();
            emailConfirmed.setErrorEnabled(false);
            emailConfirmed.requestFocus();
            password.setErrorEnabled(false);
            password.requestFocus();
            passwordConfirmed.setErrorEnabled(false);
            passwordConfirmed.requestFocus();

            if (!validateInput(firstNameValue)) {
              firstName.setError("nom non valide !");
              firstName.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!validateInput(lastNameValue)) {
              lastName.setError("prénom non valide !");
              lastName.requestFocus();
              mdperreur();
            } else if (!validateEmail(emailValue)) {
              email.setError("Email non valide !");
              email.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!validateEmail(emailConfirmedValue)) {
              emailConfirmed.setError("Email non valide !");
              emailConfirmed.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!(emailValue.equals(emailConfirmedValue))) {
              email.setError("Les deux e-mails ne sont pas identiques");
              emailConfirmed.setError("Les deux e-mails ne sont pas identiques");
              emailConfirmed.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!validatePassword(passwordValue)) {
              password.setError("Mot de passe non valide !");
              password.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!validateInput(passwordConfirmedValue)) {
              passwordConfirmed.setError("Mot de passe non valide !");
              passwordConfirmed.requestFocus();
              // hideButton();
              mdperreur();
            } else if (!(passwordValue.equals(passwordConfirmedValue))) {
              password.setError("Les deux mots de passe ne sont pas identiques");
              passwordConfirmed.setError("Les deux mots de passe ne sont pas identiques");
              passwordConfirmed.requestFocus();
              // hideButton();
              mdperreur();
            } else {
              hideKeyboard();
              doInscri(firstNameValue, lastNameValue, emailValue, passwordValue);
            }
          }
        });

    // facebook login

    callbackManager = CallbackManager.Factory.create();
    loginFacebook = (LoginButton) findViewById(R.id.login_button);
    loginManager = LoginManager.getInstance();
    loginFacebook.setReadPermissions(readPermissions);
    loginFacebook.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            hideButton();
          }
        });
    loginFacebook.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            accessToken = AccessToken.getCurrentAccessToken();
            // Log.d("user facebook",loginResult.toString());
            GraphRequest request =
                GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                      @Override
                      public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.v("LoginActivity", response.toString());
                        try {
                          User user =
                              new User(
                                  object.get("id").toString(),
                                  object.get("email").toString(),
                                  object.get("name").toString());
                          AuthUtils.saveUser(InscriptionActivity.this, user);
                          succ();
                        } catch (JSONException e) {
                          e.printStackTrace();
                        }
                      }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email");
            request.setParameters(parameters);
            request.executeAsync();
          }

          @Override
          public void onCancel() {
            Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onError(FacebookException error) {
            Toast.makeText(getBaseContext(), "error,retry again", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
            mdperreur();
          }
        });
    // google+ login

    // [START configure_signin]
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso =
        new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();

    // [START build_client]
    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient =
        new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    signInButtonGoogle = (SignInButton) findViewById(R.id.sign_in_button);
    signInButtonGoogle.setSize(SignInButton.SIZE_STANDARD);
    signInButtonGoogle.setScopes(gso.getScopeArray());

    signInButtonGoogle.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
            hideButton();
          }
        });
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.v(LOG_TAG, "OnCreateView for LoginActivity Fragment");
    View view = inflater.inflate(R.layout.fragment_landing, container, false);
    loginButtonFaceBook = (LoginButton) view.findViewById(R.id.login_button);
    signButton = (Button) view.findViewById(R.id.signup);
    loginButton = (Button) view.findViewById(R.id.login);
    loginButtonFaceBook.setReadPermissions("user_friends");
    googleButton = (com.google.android.gms.common.SignInButton) view.findViewById(R.id.google);
    // If using in a fragment
    loginButtonFaceBook.setFragment(this);
    // Other app specific specialization
    callbackManager = CallbackManager.Factory.create();
    // Callback registration
    signButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Log.v(LOG_TAG, "Signup button clicked, switching to SignUp fragment");
            getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout, new SignUpFragment())
                .commit();
          }
        });

    loginButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Log.v(LOG_TAG, "Login button clicked, switching to SplatterLogin fragment");
            getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout, new SplatterLoginFragment())
                .commit();
          }
        });

    googleButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Log.v(LOG_TAG, "Sign-in with Google clicked, switching to Google activity");
            Intent intent = new Intent(getActivity(), GoogleActivity.class);
            getActivity().startActivity(intent);
          }
        });

    loginButtonFaceBook.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.i(LOG_TAG, "Sign-in with Facebook successful");
            String username = loginResult.getAccessToken().getUserId();
            HttpAgent.tokenValue = loginResult.getAccessToken().toString();

            Log.v(
                LOG_TAG,
                String.format("Username %s, AccessToken %s", username, HttpAgent.tokenValue));
            SharedPreferences sharedPref =
                getActivity()
                    .getSharedPreferences(
                        getString(R.string.preference_file), Context.MODE_PRIVATE);
            SharedPreferences.Editor prefEdit = sharedPref.edit();
            prefEdit.putString(
                getString(R.string.login_method), getString(R.string.facebook_login));
            prefEdit.putString(getString(R.string.key_username), username);
            prefEdit.putString(getString(R.string.access_token), HttpAgent.tokenValue);
            prefEdit.apply();

            String k = JsonHandler.stringifyNormal(loginResult);
            getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout, new SelectTagsFragment())
                .commit();
          }

          @Override
          public void onCancel() {
            Log.i(LOG_TAG, "Facebook login operation cancelled");
          }

          @Override
          public void onError(FacebookException exception) {
            Log.e(LOG_TAG, "In Facebook Sign-in, got exception: ", exception);
          }
        });
    return view;
  }
Ejemplo n.º 23
0
  @Override
  public void initSignInButton(View button) {
    final LoginButton loginButton = (LoginButton) button;
    loginButton.setReadPermissions(READ_PERMISSIONS_PUBLIC_PROFILE);

    mFacebookCallback = CallbackManager.Factory.create();

    loginButton.registerCallback(
        mFacebookCallback,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            final AccessToken accessToken = loginResult.getAccessToken();

            final GraphRequest request =
                GraphRequest.newMeRequest(
                    accessToken,
                    new GraphRequest.GraphJSONObjectCallback() {
                      @Override
                      public void onCompleted(JSONObject object, GraphResponse response) {

                        final String id;
                        final String name;
                        try {
                          id = object.getString("id");
                          name = object.getString("name");
                        } catch (JSONException e) {
                          e.printStackTrace();
                          return;
                        }

                        final User user =
                            new User(
                                UserVerifierApp.AccountType.FACEBOOK,
                                id,
                                name,
                                accessToken.getToken());

                        mEventBus
                            .obtainMessage(LoginActivity.EVENT_ATTACH_USER, user)
                            .sendToTarget();
                      }
                    });

            final Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name");
            request.setParameters(parameters);
            request.executeAsync();
          }

          @Override
          public void onCancel() {
            mEventBus
                .obtainMessage(
                    LoginActivity.EVENT_ERROR, mActivity.getString(R.string.facebook_cancelled))
                .sendToTarget();
          }

          @Override
          public void onError(FacebookException exception) {
            mEventBus
                .obtainMessage(
                    LoginActivity.EVENT_ERROR,
                    mActivity.getString(R.string.facebook_error, exception.getMessage()))
                .sendToTarget();
          }
        });
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this);

    setContentView(R.layout.activity_login);
    setupUI(findViewById(R.id.layout));

    // Set up the login form.
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
    populateAutoComplete();

    mPhoneNumberView = (EditText) findViewById(R.id.phoneNumber);
    mPhoneNumberView.setVisibility(View.GONE);
    mUserIdView = (EditText) findViewById(R.id.userId);
    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(
        new TextView.OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
              attemptLogin(User.AuthenticationType.APPLOZIC);
              return true;
            }
            return false;
          }
        });

    mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View view) {

            Utils.toggleSoftKeyBoard(LoginActivity.this, true);
            attemptLogin(User.AuthenticationType.APPLOZIC);
          }
        });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions("user_friends");

    // Callback registration
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            mUserIdView.setText(loginResult.getAccessToken().getUserId());
            mPasswordView.setText(loginResult.getAccessToken().getToken());
            attemptLogin(User.AuthenticationType.FACEBOOK);
          }

          @Override
          public void onCancel() {}

          @Override
          public void onError(FacebookException exception) {}
        });

    mSpinnerView = (Spinner) findViewById(R.id.spinner_for_url);
    mSpinnerView.setVisibility(View.INVISIBLE);
    mTitleView = (TextView) findViewById(R.id.textViewTitle);
    mTitleView.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View view) {
            touchCount += 1;
            if (touchCount == 5) {
              mSpinnerView.setVisibility(View.VISIBLE);
              touchCount = 0;

            } else {
              Toast.makeText(
                      getApplicationContext(),
                      "Click more  " + Integer.toString(5 - touchCount),
                      Toast.LENGTH_SHORT)
                  .show();
            }
          }
        });

    mobiComUserPreference = MobiComUserPreference.getInstance(this);
    mSpinnerView.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            mobiComUserPreference.setUrl(adapterView.getItemAtPosition(i).toString());
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {}
        });
  }
Ejemplo n.º 25
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    setContentView(R.layout.activity_main);

    Typeface reminiscence = Typeface.createFromAsset(getAssets(), "fonts/Existence-Light.ttf");
    TextView title = (TextView) findViewById(R.id.title);
    title.setTypeface(reminiscence);

    final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    final RadioButton therapist = (RadioButton) findViewById(R.id.therapist);
    final RadioButton patient = (RadioButton) findViewById(R.id.patient);
    final RadioButton family = (RadioButton) findViewById(R.id.family);

    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_photos");
    loginButton.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(final LoginResult loginResult) {
            // App code

            GraphRequest request =
                GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                      @Override
                      public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {

                        try {
                          String name = jsonObject.getString("name");
                          SharedPreferences preferences = getSharedPreferences("name", 0);
                          SharedPreferences.Editor edit = preferences.edit();
                          edit.putString("name", name);
                        } catch (JSONException e) {
                          Log.d("ERROR IN GRAPH REQUEST", e.getMessage());
                        }
                      }
                    });

            Bundle parameters = new Bundle();
            parameters.putString("fields", "name");
            request.setParameters(parameters);
            request.executeAsync();

            int selectedId = radioGroup.getCheckedRadioButtonId();

            if (selectedId == therapist.getId()) {
              Intent intent = new Intent(MainActivity.this, TherapistMainActivity.class);
              intent.putExtra("EXTRA_FB_ACCESS_TOKEN", loginResult.getAccessToken());
              startActivity(intent);
              finish();
            } else if (selectedId == patient.getId()) {
              // do action here
            } else if (selectedId == family.getId()) {
              Intent intent = new Intent(MainActivity.this, FamilyActivity.class);
              intent.putExtra("EXTRA_FB_ACCESS_TOKEN", loginResult.getAccessToken());
              startActivity(intent);
              finish();
            }
          }

          @Override
          public void onCancel() {
            // App code
          }

          @Override
          public void onError(FacebookException exception) {
            // App code
          }
        });
  }
Ejemplo n.º 26
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);
    ButterKnife.bind(this);
    session = new SessionManager(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions(Arrays.asList("user_status", "email"));
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email"));
    LoginManager.getInstance().registerCallback(callbackManager, this);

    if (BuildConfig.DEBUG) {
      // we only want to show the logs in debug builds, for easier debugging
      Stormpath.setLogLevel(StormpathLogger.VERBOSE);
    }

    // initialise login button below
    _loginButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            login();
          }
        });

    // intialise Register link below
    _registerLink.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // Start register activity
            Toast.makeText(getApplicationContext(), "Register is selected!", Toast.LENGTH_SHORT)
                .show();
            Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
            startActivityForResult(intent, REQUEST_REGISTER);
          }
        });

    _skiploginLink.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // Start register activity
            Toast.makeText(getApplicationContext(), "Skipping login!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
          }
        });

    String serverClientId = getString(R.string.goog_app_id);
    GoogleSignInOptions gso =
        new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(Scopes.EMAIL))
            .requestServerAuthCode(serverClientId, false)
            .build();

    mGoogleApiClient =
        new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_STANDARD);
    signInButton.setScopes(gso.getScopeArray());

    signInButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Log.d("google click", "test ");
            signIn();
          }
        });
  }
Ejemplo n.º 27
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ParseUser mCurrentUser = ParseUser.getCurrentUser();

    // if a user has not yet logged in, take them to the login screen
    // otherwise go straight to the MainAcitivty
    if (mCurrentUser == null) {
      // We could also use "user_birthday" as another parameter
      // but this requires Facebook to review the app and allow it to use this permission
      final List<String> mPermissions = Arrays.asList("public_profile", "email");

      mFbButton = (LoginButton) findViewById(R.id.fb_login_button);
      mFbButton.setReadPermissions(mPermissions);

      mLoginFormView = (ScrollView) findViewById(R.id.login_form);
      mProgressView = (ProgressBar) findViewById(R.id.login_progress);

      mFbButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              // check whether or not user has internet access to log in with FB
              ConnectivityManager cm =
                  (ConnectivityManager)
                      LoginActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
              if (activeNetwork != null
                  && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE
                      || activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)) {
                // User is connected to the internet
                // show a loading circle while getting the data from Fb
                // Otherwise the user will see the login screen while tasks are happening in the
                // background
                // and might think something went wrong
                showProgress(true);
                ParseFacebookUtils.logInWithReadPermissionsInBackground(
                    LoginActivity.this,
                    mPermissions,
                    new LogInCallback() {
                      @Override
                      public void done(ParseUser user, ParseException err) {
                        if (err == null) {
                          if (user == null) {
                            showProgress(false);
                            Log.d(LOG_TAG, "Uh oh. The user cancelled the Facebook login.");
                          } else if (user.isNew()) {
                            Log.d(LOG_TAG, "User signed up and logged in through Facebook!");
                            getUserDetailsFromFB();
                          } else {
                            Log.d(LOG_TAG, "User logged in through Facebook!");
                            getUserDetailsFromParse();
                          }
                        } else {
                          showProgress(false);
                          err.printStackTrace();
                        }
                      }
                    });
              } else {
                // User is not connected to the internet
                Toast.makeText(
                        LoginActivity.this,
                        "You can't log in with Facebook without an internet connection",
                        Toast.LENGTH_SHORT)
                    .show();
              }
            }
          });

      // Set up the login form.
      mEmailView = (EditText) findViewById(R.id.email);

      mPasswordView = (EditText) findViewById(R.id.password);
      mPasswordView.setOnEditorActionListener(
          new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
              if (id == getResources().getInteger(R.integer.login_ime_id)
                  || id == EditorInfo.IME_NULL) {
                hideKeyboard();
                return true;
              }
              return false;
            }
          });

      Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
      mSignInButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View view) {
              hideKeyboard();
              checkFieldValidity(0);
            }
          });

      Button mRegisterButton = (Button) findViewById(R.id.register_button);
      mRegisterButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View view) {
              hideKeyboard();
              checkFieldValidity(1);
            }
          });

      final CheckBox mCheckboxView = (CheckBox) findViewById(R.id.showPasswordCheckbox);
      mCheckboxView.setOnCheckedChangeListener(
          new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              if (!isChecked) {
                mPasswordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
              } else {
                // hide password
                mPasswordView.setTransformationMethod(
                    HideReturnsTransformationMethod.getInstance());
              }
            }
          });

      hideKeyboard();
      // }
    } else {
      startMainActivity();
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // for finding key hash of dev environment
    // Log.i(TAG, printKeyHash(this));
    pref = getSharedPreferences(Constants.SHARED_PREFERENCE, Context.MODE_PRIVATE);
    // initializing facebook sdk
    FacebookSdk.sdkInitialize(this.getApplicationContext());

    // setting the layout
    setContentView(R.layout.activity_login);

    Button clickButton = (Button) findViewById(R.id.inst);
    final TypedValue typedValue = new TypedValue();
    clickButton.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            String mssg =
                "1. Login with facebook.\n"
                    + "2. This app will work only if other users are also on the same wifi network."
                    + "3. Select discover tab for seeing people around"
                    + "4. Select Match tab for seeing all your matches and chat with them by tapping on matches"
                    + "5. view your profile and preferences from action overflow"
                    + "6. logout by clicking logout button in action overflow";
            AlertDialog.Builder myAlert = new AlertDialog.Builder(LoginActivity.this);

            myAlert
                .setMessage(mssg)
                .setNeutralButton(
                    "Continue..",
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                      }
                    })
                .setTitle("!Instructions For You!")
                .setIcon(typedValue.resourceId)
                .create();
            myAlert.show();
          }
        });
    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    // System.setProperty("http.keepAlive", "false");

    // login button reference
    loginButton = (LoginButton) findViewById(R.id.login_button);

    // registering callback manager
    callbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(callbackManager, loginCallback());

    // setting permissions of login button
    loginButton.setReadPermissions(
        "user_photos", "user_about_me", "user_birthday", "user_location", "user_posts");

    WifiManager wifi_manager = (WifiManager) this.getSystemService(this.WIFI_SERVICE);
    if (!wifi_manager.isWifiEnabled()) {
      Toast.makeText(this, "enable your wifi", Toast.LENGTH_SHORT).show();
      AppServer.getInstance(this).killServer();
      NSDHelper.getInstance(this).tearDown();
      MessageClientHelper.getInstance(this).terminateMessageClient();
      // LoginManager.getInstance().logOut();
      finish();

    } else {

      // getting current access token
      accessToken = AccessToken.getCurrentAccessToken();

      //
      if (accessToken != null && accessToken.isExpired()) {
        LoginManager.getInstance()
            .logInWithReadPermissions(
                this,
                Arrays.asList(
                    "user_photos",
                    "user_about_me",
                    "user_birthday",
                    "user_location",
                    "user_posts"));
      } else if (accessToken != null && !accessToken.isExpired()) {
        // getPermanentToken();
        requestProfileInfo();
        // enterMainApp();
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_main);

    callbackManager = CallbackManager.Factory.create();
    login = (LoginButton) findViewById(R.id.login_button);
    profile = (ProfilePictureView) findViewById(R.id.picture);
    shareDialog = new ShareDialog(this);
    share = (Button) findViewById(R.id.share);
    details = (Button) findViewById(R.id.details);
    login.setReadPermissions("public_profile email");
    share.setVisibility(View.INVISIBLE);
    details.setVisibility(View.INVISIBLE);
    details_dialog = new Dialog(this);
    details_dialog.setContentView(R.layout.dialog_details);
    details_dialog.setTitle("Details");
    details_txt = (TextView) details_dialog.findViewById(R.id.details);
    details.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            details_dialog.show();
          }
        });

    if (AccessToken.getCurrentAccessToken() != null) {
      RequestData();
      share.setVisibility(View.VISIBLE);
      details.setVisibility(View.VISIBLE);
    }
    login.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            if (AccessToken.getCurrentAccessToken() != null) {
              share.setVisibility(View.INVISIBLE);
              details.setVisibility(View.INVISIBLE);
              profile.setProfileId(null);
            }
          }
        });
    share.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            ShareLinkContent content = new ShareLinkContent.Builder().build();
            shareDialog.show(content);
          }
        });
    login.registerCallback(
        callbackManager,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {

            if (AccessToken.getCurrentAccessToken() != null) {
              RequestData();
              share.setVisibility(View.VISIBLE);
              details.setVisibility(View.VISIBLE);
            }
          }

          @Override
          public void onCancel() {}

          @Override
          public void onError(FacebookException exception) {}
        });
  }
Ejemplo n.º 30
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && checkSelfPermission(Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED
        && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
      requestPermissions(
          new String[] {
            Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE
          },
          PERMISSIONS_REQUEST_READ_CONTACTS);
      Toast.makeText(getApplicationContext(), "permission requested", Toast.LENGTH_LONG);
    }
    int PERMISSIONS_REQUEST_INTERNET = 300;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
      requestPermissions(new String[] {Manifest.permission.INTERNET}, PERMISSIONS_REQUEST_INTERNET);
      Toast.makeText(getApplicationContext(), "permission requested", Toast.LENGTH_LONG);
    }
    super.onCreate(savedInstanceState);
    /* Initialize facebook sdk */
    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManger = CallbackManager.Factory.create();
    setContentView(R.layout.activity_main);

    if (com.facebook.AccessToken.getCurrentAccessToken() != null) {
      gotoMainActivity();
    }
    //        email = (EditText)findViewById(R.id.email);
    //        password = (EditText)findViewById(R.id.password);

    try {
      PackageInfo info =
          getPackageManager()
              .getPackageInfo("com.facebook.samples.hellofacebook", PackageManager.GET_SIGNATURES);
      for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
      }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
    /* Initialize facebook login */
    final LoginButton loginButton = (LoginButton) findViewById(R.id.facebook_login);
    loginButton.setReadPermissions("public_profile", "user_friends", "email");

    loginButton.registerCallback(
        callbackManger,
        new FacebookCallback<LoginResult>() {
          @Override
          public void onSuccess(LoginResult loginResult) {
            Log.d("Token", loginResult.getAccessToken().getToken());
            Log.d("TokenId", loginResult.getAccessToken().getUserId());
            RestAdapter adapter =
                new RestAdapter(getApplicationContext(), "http://52.78.69.111:3000/api/");
            PersonRepository personRepository = adapter.createRepository(PersonRepository.class);
            String token = loginResult.getAccessToken().getToken();
            String uid = loginResult.getAccessToken().getUserId();
            personRepository.fblogin(
                token,
                uid,
                new VoidCallback() {
                  @Override
                  public void onSuccess() {
                    gotoMainActivity();
                  }

                  @Override
                  public void onError(Throwable t) {}
                });
          }

          @Override
          public void onCancel() {}

          @Override
          public void onError(FacebookException error) {}
        });

    //        login = (Button)findViewById(R.id.buttonLogin);
    //        int success=1;
    //        //If login already
    //        if (success==1) {
    //            login.setOnClickListener(new View.OnClickListener(){
    //                @Override
    //                public void onClick(View view){
    //                    emailtxt = email.getText().toString();
    //                    passtxt = password.getText().toString();

    //                params = new ArrayList<NameValuePair>();
    //                params.add(new BasicNameValuePair("email", emailtxt));
    //                params.add(new BasicNameValuePair("password",passtxt));
    //                ServerRequest sr = new ServerRequest();
    //                JSONObject json = sr.getJSON("https://52.78.73.214:3000/login",params);
    //                if(json!=null){
    //                    try{
    //                        String jsonstr = json.getString("response");
    //                        if(json.getBoolean("res")){
    //
    //                        }
    //                    }catch(JSONException e){
    //                        e.printStackTrace();
    //                    }
    //                }

    //                    gotoMainActivity();
    //                }
    //            });
    //        }else if(success==0) {
    //
    //        }else {
    //            gotoMainActivity();
    //        }
    //
  }