简体   繁体   English

在Android应用程序中集成Facebook

[英]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); 这在模拟器上工作正常,但是fb登录在其中没有使用Facebook应用程序的手机上无法正常工作,我在某处读取了我需要使用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. 因为我认为没有使用正确的程序包名称正确安装哈希键,所以请使用以下URL。

Android facebook login not working with installed Facebook app Android Facebook登录不适用于已安装的Facebook应用

Hashkey Implementation on oncreate method of your main activity: 您主要活动的oncreate方法的Hashkey实现:

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. 使用此代码可与已安装的facebook应用程序一起使用。

 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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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