简体   繁体   中英

facebook integration in android app

public class MainActivity extends ActionBarActivity {

   // FACEBOOK INTEGRATION INITIALIZATION
    CallbackManager callbackManager;
    LoginButton fbLoginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        setContentView(R.layout.activity_main);
        fbLoginButton=(LoginButton) findViewById(R.id.fb_login_button);


 //FACEBOOK FUNCTION FOR LOGIN

        fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                System.out.println("Facebook Login Successful!");
                System.out.println("Logged in user Details : ");
                System.out.println("--------------------------");
                System.out.println("User ID  : " + loginResult.getAccessToken().getUserId());
                System.out.println("Authentication Token : " + loginResult.getAccessToken().getToken());
                Toast.makeText(MainActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");
            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");
            }
        });



//INITIALIZATION OF BUTTONS
        Button button;
        final EditText edit_name,edit_pass,edit_email,edit_phone;
        final CheckBox check;
        SharedPreferences pref;
         final Editor editor;

//INSTANCES
        button=(Button)findViewById(R.id.button);
        edit_name=(EditText)findViewById(R.id.edit_name);
        edit_pass=(EditText)findViewById(R.id.edit_pass);
        edit_email=(EditText)findViewById(R.id.edit_email);
        edit_phone=(EditText)findViewById(R.id.edit_phone);
        check=(CheckBox)MainActivity.this.findViewById(R.id.checkBox);
        pref=getSharedPreferences("Registration",0);
        editor=pref.edit();

//CHECKBOX FUNTION

       check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if(!check.isChecked())
               {
                   edit_pass.setTransformationMethod(new PasswordTransformationMethod());
               }
               else
               {
                   edit_pass.setTransformationMethod(null);
               }
           }
       });


//BUTTONS

               button.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       boolean flag =true;
                       String name=edit_name.getText().toString();
                       String email=edit_email.getText().toString();
                       String pass=edit_pass.getText().toString();
                       String phone=edit_phone.getText().toString();


                       if(!isValidEmail(email))
                        {
                           edit_email.setError("Invalid Email");
                           flag=false;
                        }
                       if(!isValidPassword(pass))
                       {
                           edit_pass.setError("Invalid Password");
                           flag=false;
                       }
                       if (!isValidPhone(phone))
                       {
                           edit_phone.setError("Invalid phone");
                           flag=false;
                       }



                       if(flag==true)
                       {
                           Toast.makeText(getApplicationContext(), "LOGIN SUCCESSFUL", Toast.LENGTH_SHORT).show();
                           editor.putString("Name", name);
                           editor.putString("Email", email);
                           editor.putString("phone",phone);
                           editor.putString("password",pass);
                           editor.commit();
                           Intent i = new Intent(MainActivity.this,upload_photo.class);
                           startActivity(i);

                       }
                       else
                       {
                           Toast.makeText(getApplicationContext(),"LOGIN UNSUCCESSFUL",Toast.LENGTH_SHORT).show();
                       }
                   }
               });

    }

//FUNCTIONS

    private boolean isValidEmail(String email)
    {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern=Pattern.compile(EMAIL_PATTERN);
        Matcher matcher=pattern.matcher(email);
        return matcher.matches();
    }

    private boolean isValidPassword(String password)
    {
        if(password!=null && password.length()>6)
        {
            return true;
        }
        else
            return false;
    }

    private boolean isValidPhone(String phone)
    {
        if (phone.length()==10)
        {
            return true;
        }

        return false;
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent i) {
        callbackManager.onActivityResult(reqCode, resCode, i);
    }    
}

this is working fine on emulator, but fb login is not working on phone with facebook app in it ,i read somewhere that i need to use facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, this);
but dont know where to use that , can you please help me in that???

Please go with the below URL as I thought the hashkey is not installed properly with the proper package name.

Android facebook login not working with installed Facebook app

Hashkey Implementation on oncreate method of your main activity:

PackageInfo info;

     try {
            info = activity.getPackageManager().getPackageInfo("com.checkmyplanner", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md;
                md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String something = new String(Base64.encode(md.digest(), 0));
                //String something = new String(Base64.encodeBytes(md.digest()));
                Log.e("hash key", something);
            }
        } catch (NameNotFoundException e1) {
            Log.e("name not found", e1.toString());
        } catch (NoSuchAlgorithmException e) {
            Log.e("no such an algorithm", e.toString());
        } catch (Exception e) {
            Log.e("exception", e.toString());
        }

Any help will be needed, do let me know.

use this code it's works with already installed facebook application.

 callbackManager = CallbackManager.Factory.create(); loginButton = (LoginButton) findViewById(R.id.login_button); List < String > permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile", "AccessToken"); loginButton.registerCallback(callbackManager, new FacebookCallback < LoginResult > () {@Override public void onSuccess(LoginResult loginResult) { System.out.println("onSuccess"); String accessToken = loginResult.getAccessToken() .getToken(); Log.i("accessToken", accessToken); GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {@Override public void onCompleted(JSONObject object, GraphResponse response) { Log.i("LoginActivity", response.toString()); try { String id = object.getString("id"); try { URL profile_pic = new URL( "http://graph.facebook.com/" + id + "/picture?type=large"); Log.i("profile_pic", profile_pic + ""); } catch (MalformedURLException e) { e.printStackTrace(); } String name = object.getString("name"); String email = object.getString("email"); String gender = object.getString("gender"); String birthday = object.getString("birthday"); } 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) { System.out.println("onError"); Log.v("LoginActivity", exception.getCause().toString()); } }); 

 @Override protected void onActivityResult(int requestCode, int responseCode, Intent data) { super.onActivityResult(requestCode, responseCode, data); callbackManager.onActivityResult(requestCode, responseCode, data); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM