无法从Facebook SDK Android获取用户位置

时间:2014-10-10 10:28:22

标签: java android facebook

我希望通过Facebook登录获取用户在我的Android应用程序中的位置。我实现了登录,除了位置之外一切正常(用户在他的个人资料中更新的位置为"生活在")。我使用this检索了用户名和id。我也设置了权限。但它没有工作。请帮助我。

这是我的班级

public class FacebookActivity extends Activity implements OnClickListener 
{
    Facebook fb;
    //ImageView pic;

    CircularImageView pic;
    ImageView button;
    TextView welcome,location;
    SharedPreferences sp;
    String APP_ID = "xxxxxxxx";
    String name;
    String id;
    String town;
    String currentCity;
    String imgurl_check;
    Drawable d ;
    Bitmap bitmap;
    String access_token;


    @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            fb = new Facebook(APP_ID);

            sp = getPreferences(MODE_PRIVATE);
            access_token = sp.getString("access_token", null);
            long expires = sp.getLong("access_expires", 0);

            if(access_token !=null)
            {
                fb.setAccessToken(access_token);

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

            button = (ImageView) findViewById(R.id.login);
            welcome = (TextView) findViewById(R.id.name);
            location = (TextView) findViewById(R.id.location);
            //pic = (ImageView) findViewById(R.id.picture_pic);
            pic = (CircularImageView) findViewById(R.id.picture_pic);

            button.setOnClickListener(this);

            updateButtonImage();

        }

     private void updateButtonImage() 
        {
         if(fb.isSessionValid())
            {
                //button.setImageResource(R.drawable.fb_logout);
                button.setVisibility(View.INVISIBLE);


                new GetProfileName().execute();
                new LoadProfileImage(pic)
                .execute("https://graph.facebook.com/me/picture?width=200&height=200&method=GET&access_token="
                        + access_token);

                //pic.setVisibility(View.VISIBLE);  
                    }
         else
         {
                button.setImageResource(R.drawable.fb_login);
                welcome.setVisibility(View.INVISIBLE);
                pic.setVisibility(View.INVISIBLE);
            }
        }


private class GetProfileName extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls)
         {

            JSONObject obj = null;
            JSONObject obj1 = null;

            URL img_url = null;

            String jsonUser;
            String jsonPicture;

                try {
                    jsonUser = fb.request("me");
                    obj = Util.parseJson(jsonUser);
                    id = obj.optString("id");
                    name = obj.optString("name");
                    currentCity = obj.getJSONObject("location").getString("name");

                 Log.d("Executing thread",id);
                 Log.d("Executing thread",name);
                 Log.d("Executing thread",currentCity);



                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FacebookError e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }



          return null;

             }
         protected void onProgressUpdate(Integer... progress) {

             }
         protected void onPostExecute(Long result) {



             location.setText(currentCity);
             location.setVisibility(View.VISIBLE);
                welcome.setText(name);
                welcome.setVisibility(View.VISIBLE);

                sp = getPreferences(MODE_PRIVATE);
                final SharedPreferences.Editor editor = sp.edit();

                editor.putString("UserName", name);

                editor.commit();


             }
        }

/**
* Background Async task to load user profile picture from url
* */
  private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
    CircularImageView bmImage;

  public LoadProfileImage(CircularImageView bmImage) {
this.bmImage = bmImage;

}

protected Bitmap doInBackground(String... urls) {

String urldisplay = urls[0];
Bitmap mIcon11 = null;

try {

    InputStream in = new java.net.URL(urldisplay).openStream();
    mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
    Log.e("Error", e.getMessage());
    e.printStackTrace();
}

return mIcon11;



}

protected void onPostExecute(Bitmap result) {

bmImage.setImageBitmap(result);
pic.setVisibility(View.VISIBLE);    
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/App");

if (!mFolder.exists()) {
    mFolder.mkdir();
}

String s = "myfile.png";

File f = new File(mFolder.getAbsolutePath(),s);

String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(f);
    result.compress(Bitmap.CompressFormat.PNG,70, fos);

    fos.flush();
    fos.close();
 //   MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {

    e.printStackTrace();
} catch (Exception e) {

    e.printStackTrace();
}

}
}
    @Override
    public void onClick(View v) 
    {
        if(fb.isSessionValid())
        {
                    try {
                        fb.logout(getApplicationContext());
                        updateButtonImage();

                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                }
     else
     {
            //login to fb

            fb.authorize(FacebookActivity.this,new String[] {"email","user_hometown","user_location"},new DialogListener() {

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(FacebookActivity.this,  "fberror", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onError(DialogError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(FacebookActivity.this,  "onerror", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onComplete(Bundle values) {
                    // TODO Auto-generated method stub
                    Editor editor = sp.edit();
                    editor.putString("access_token", fb.getAccessToken());
                    editor.putLong("access_expires", fb.getAccessExpires());
                    editor.commit();
                    updateButtonImage();

                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub
                    Toast.makeText(FacebookActivity.this,  "Oncancel", Toast.LENGTH_SHORT).show();

                }
            });


        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        fb.authorizeCallback(requestCode, resultCode, data);
    }

}

1 个答案:

答案 0 :(得分:0)

从这里下载源代码:

https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/

添加此依赖项:

compile 'com.facebook.android:facebook-android-sdk:4.0.1'

<强> activity_main.xml中

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/iv_image"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/profile"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:text="Name"
            android:gravity="center_vertical"
            android:textSize="15dp"
            android:textColor="#000000"

            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Name"
            android:textSize="15dp"
            android:id="@+id/tv_name"
            android:gravity="center_vertical"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>

    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:text="Email"
        android:gravity="center_vertical"
        android:textSize="15dp"
        android:layout_below="@+id/tv_name"
        android:textColor="#000000"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_below="@+id/tv_name"
        android:text="Email"
        android:gravity="center_vertical"
        android:textSize="15dp"
        android:id="@+id/tv_email"
        android:textColor="#000000"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:text="DOB"
            android:gravity="center_vertical"
            android:textSize="15dp"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_below="@+id/tv_name"
            android:text="DOB"
            android:gravity="center_vertical"
            android:textSize="15dp"
            android:id="@+id/tv_dob"
            android:layout_toRightOf="@+id/tv_email"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:text="Location"
            android:gravity="center_vertical"
            android:textSize="15dp"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_below="@+id/tv_name"
            android:text="location"
            android:gravity="center_vertical"
            android:textSize="15dp"
            android:id="@+id/tv_location"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"/>
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:background="#6585C8"
        android:id="@+id/ll_facebook"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="40dp"
        android:layout_height="50dp">

        <ImageView
            android:layout_width="50dp"
            android:src="@drawable/facebook"
            android:id="@+id/iv_facebook"
            android:layout_height="50dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login with Facebook"
            android:textSize="20dp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"
            android:id="@+id/tv_facebook"
            android:layout_marginLeft="20dp"
            android:gravity="center"
            android:layout_gravity="center"

            />

    </LinearLayout>

    </LinearLayout>

<强> MainActivity.java

package facebooklocation.facebooklocation;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    CallbackManager callbackManager;
    ImageView iv_image, iv_facebook;
    TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
    LinearLayout ll_facebook;
    String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
    boolean boolean_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        getKeyHash();
        listener();
    }


    private void init() {
        iv_image = (ImageView) findViewById(R.id.iv_image);
        iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_dob = (TextView) findViewById(R.id.tv_dob);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_facebook = (TextView) findViewById(R.id.tv_facebook);
        ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
        FacebookSdk.sdkInitialize(this.getApplicationContext());
    }

    private void listener() {
        tv_facebook.setOnClickListener(this);
        ll_facebook.setOnClickListener(this);
        iv_facebook.setOnClickListener(this);

    }

    private void facebookLogin() {
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
                        + "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
                );
                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                try {

                                    boolean_login = true;
                                    tv_facebook.setText("Logout from Facebook");

                                    Log.e("object", object.toString());
                                    str_facebookname = object.getString("name");

                                    try {
                                        str_facebookemail = object.getString("email");
                                    } catch (Exception e) {
                                        str_facebookemail = "";
                                        e.printStackTrace();
                                    }

                                    try {
                                        str_facebookid = object.getString("id");
                                    } catch (Exception e) {
                                        str_facebookid = "";
                                        e.printStackTrace();

                                    }


                                    try {
                                        str_birthday = object.getString("birthday");
                                    } catch (Exception e) {
                                        str_birthday = "";
                                        e.printStackTrace();
                                    }

                                    try {
                                        JSONObject jsonobject_location = object.getJSONObject("location");
                                        str_location = jsonobject_location.getString("name");

                                    } catch (Exception e) {
                                        str_location = "";
                                        e.printStackTrace();
                                    }

                                    fn_profilepic();

                                } catch (Exception e) {

                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, name, email,gender,birthday,location");

                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                if (AccessToken.getCurrentAccessToken() == null) {
                    return; // already logged out
                }
                new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
                        .Callback() {
                    @Override
                    public void onCompleted(GraphResponse graphResponse) {
                        LoginManager.getInstance().logOut();
                        LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
                        facebookLogin();

                    }
                }).executeAsync();


            }

            @Override
            public void onError(FacebookException e) {
                Log.e("ON ERROR", "Login attempt failed.");


                AccessToken.setCurrentAccessToken(null);
                LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        try {
            callbackManager.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {

        }

    }

    private void getKeyHash() {
        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", 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) {

        }
    }

    private void fn_profilepic() {

        Bundle params = new Bundle();
        params.putBoolean("redirect", false);
        params.putString("type", "large");
        new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "me/picture",
                params,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {

                        Log.e("Response 2", response + "");

                        try {
                            String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
                            Log.e("Picture", str_facebookimage);

                            Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        tv_name.setText(str_facebookname);
                        tv_email.setText(str_facebookemail);
                        tv_dob.setText(str_birthday);
                        tv_location.setText(str_location);

                    }
                }
        ).executeAsync();
    }


    @Override
    public void onClick(View view) {

        if (boolean_login) {
            boolean_login = false;
            LoginManager.getInstance().logOut();
            tv_location.setText("");
            tv_dob.setText("");
            tv_email.setText("");
            tv_name.setText("");
            Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
            tv_facebook.setText("Login with Facebook");
        } else {
            LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
            facebookLogin();
        }


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoginManager.getInstance().logOut();
    }
}

由于