Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Facebook SDK 3.20.0-只有管理员可以共享,但其他用户不能共享_Android_Facebook_Facebook Graph Api - Fatal编程技术网

Android Facebook SDK 3.20.0-只有管理员可以共享,但其他用户不能共享

Android Facebook SDK 3.20.0-只有管理员可以共享,但其他用户不能共享,android,facebook,facebook-graph-api,Android,Facebook,Facebook Graph Api,我正在尝试从我的应用程序中使用android Facebook sdk在Facebook墙上共享图像和文本。用户可以使用facebook帐户成功登录,但当尝试在墙上共享时,他被拒绝发布。当我使用管理员帐户登录时,我可以成功登录并在facebook上共享 这是我在facebook上分享的代码 public class FacebookShareActivity extends Activity { private static final String PERMISSION = "publish

我正在尝试从我的应用程序中使用android Facebook sdk在Facebook墙上共享图像和文本。用户可以使用facebook帐户成功登录,但当尝试在墙上共享时,他被拒绝发布。当我使用管理员帐户登录时,我可以成功登录并在facebook上共享

这是我在facebook上分享的代码

public class FacebookShareActivity extends Activity {

private static final String PERMISSION = "publish_actions";

private Bundle mExtras;
private String mPostText;
public ImageView mImageView;
public TextView mPostTextView;
private UiLifecycleHelper uiHelper;
private Boolean mPendingAction;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_facebook_share);

    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);
    mPendingAction = false;

    // Used to print the hash key
    getHashKey();

    // Get the intent that started this activity
    Intent intent = getIntent();
    mExtras = intent.getExtras();
    if ((mExtras == null) || mExtras.size() < 1)
    {
        // Nae extras!!! nothing to share, git tae!
        finish();
    }
    else if (!mExtras.getString(Intent.EXTRA_TEXT).isEmpty())
    {
        mPostTextView = (TextView)findViewById(R.id.postText);
        mPostText = mExtras.getString(Intent.EXTRA_TEXT);
        mPostTextView.setText(mPostText);
        mImageView = (ImageView)findViewById(R.id.imagePreview_container);
        mImageView.setImageURI((Uri) mExtras.get(Intent.EXTRA_STREAM));
    }
}

private void getHashKey()
{
    // Used for test purposes.
    // Need to set this in facebook https://developers.facebook.com/apps/ under key hashes in the android platform.
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getString(R.string.app_package_name), PackageManager.GET_SIGNATURES);

        for (Signature signature : info.signatures)
        {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA");

                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            } catch (NoSuchAlgorithmException nsa)
            {
                Log.d("exception" , "No algorithmn");
                Assert.assertTrue(false);
            }
        }
    } catch (PackageManager.NameNotFoundException nnfe)
    {
        Log.d("exception" , "Name not found");
        Assert.assertNull("Name not found", nnfe);
    }
}

public void postButtonPressed(View view)
{
    Toast.makeText(this, "Sharing to Facebook", Toast.LENGTH_SHORT).show();
    mPendingAction = true;
    Session session = Session.getActiveSession();
    if (session == null) {
        session = new Session(getApplicationContext());
        @SuppressWarnings("unused")
        Session.OpenRequest openSessionRequest = new Session.OpenRequest(this);
    }
    else
    {
        if (session.getState().equals(SessionState.CREATED))
        {
            // Session is not opened or closed, session is created but not opened.
            session = new Session(this);
            Session.setActiveSession(session);
            session.openForPublish(new Session.OpenRequest(this).setCallback(callback).setPermissions(PERMISSION));
        }
        else
        {
            onSessionStateChange(session, session.getState(), null);
        }
    }
    Session.setActiveSession(session);
}

private void onSessionStateChange(Session session, SessionState state, Exception exception)
{
    if(exception != null)
    {
        // Handle exception here.
        Log.v("Facebook CALLBACK", "Facebook login error " + exception);
        return;
    }
    if (state != null && state.isOpened()) {

        if (session.isPermissionGranted(PERMISSION))
        {
            if (mPendingAction)
            {
                // Session ready to make requests.
                postImageToFacebook();
                mPendingAction = false;
            }
        }
        else
        {
            // Get the permissions if we don't have them.
            try {
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Access denied for publish.", Toast.LENGTH_LONG).show();
            }

        }
    }
    else if (state.isClosed())
    {
        // Session logged out.
        return;
    }
}


private void postImageToFacebook() {
    Session session = Session.getActiveSession();
    final Uri uri = (Uri) mExtras.get(Intent.EXTRA_STREAM);
    final String extraText = mPostTextView.getText().toString();
    if (session.isPermissionGranted("publish_actions"))
    {
        Bundle param = new Bundle();

        // Add the image
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArrayData = stream.toByteArray();
            param.putByteArray("picture", byteArrayData);
        } catch (IOException ioe) {
            // The image that was send through is now not there?
            Assert.assertTrue(false);
        }

        // Add the caption
        param.putString("message", extraText);
        Request request = new Request(session,"me/photos", param, HttpMethod.POST, new Request.Callback() {
            @Override
            public void onCompleted(Response response) {
                addNotification(getString(R.string.photo_post), response.getGraphObject(), response.getError());

            }
        }, null);
        RequestAsyncTask asyncTask = new RequestAsyncTask(request);
        asyncTask.execute();
        clearToken();
        finish();
    }
}
private void clearToken() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
    }
}
private void addNotification(String message, GraphObject result, FacebookRequestError error)
{
    String title = null;
    String alertMessage = null;
    if (error == null) {
        title = getString(R.string.success);
        String id = result.cast(GraphObjectWithId.class).getId();
        alertMessage = getString(R.string.successfully_posted_post, message, id);
    } else {
        title = getString(R.string.error);
        alertMessage = error.getErrorMessage();
    }

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title)
                    .setContentText(alertMessage);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, MainActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    int mId = 0;
    mNotificationManager.notify(mId, mBuilder.build());
}

private interface GraphObjectWithId extends GraphObject {
    String getId();
}

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception)
    {
        onSessionStateChange(session, state, exception);
    }
};

@Override
public void onResume() {
    super.onResume();
    // For scenarios where the main activity is launched and user
    // session is not null, the session state change notification
    // may not be triggered. Trigger it if it's open/closed.
    Session session = Session.getActiveSession();
    if (session != null && (session.isOpened() || session.isClosed())) {
        onSessionStateChange(session, session.getState(), null);
    }
    uiHelper.onResume();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}
}
公共类FacebookShareActivity扩展了活动{
私有静态最终字符串权限=“发布\u操作”;
私有束mExtras;
私有字符串mPostText;
公共图像视图mImageView;
公共文本视图mPostTextView;
私人UiLifecycleHelper uiHelper;
私有布尔映射;
@SuppressLint(“新API”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u facebook\u share);
uiHelper=新UiLifecycleHelper(此为回调);
uiHelper.onCreate(savedInstanceState);
mPendingAction=false;
//用于打印哈希键
getHashKey();
//获取启动此活动的意图
Intent=getIntent();
mExtras=intent.getExtras();
if((mExtras==null)| | mExtras.size()<1)
{
//没有多余的!!!没什么可分享的,吉泰!
完成();
}
else if(!mExtras.getString(Intent.EXTRA_TEXT).isEmpty())
{
mPostTextView=(TextView)findViewById(R.id.postText);
mPostText=mExtras.getString(Intent.EXTRA_TEXT);
setText(mPostText);
mImageView=(ImageView)findViewById(R.id.imagePreview\u容器);
setImageURI((Uri)mExtras.get(Intent.EXTRA_STREAM));
}
}
私有void getHashKey()
{
//用于测试目的。
//需要在facebook中设置此选项https://developers.facebook.com/apps/ 在android平台的密钥哈希下。
试一试{
PackageInfo=getPackageManager().getPackageInfo(getString(R.string.app_package_name),PackageManager.GET_签名);
用于(签名:信息签名)
{
试一试{
MessageDigest md=MessageDigest.getInstance(“SHA”);
md.update(signature.toByteArray());
Log.d(“KeyHash:,Base64.encodeToString(md.digest(),Base64.DEFAULT));
}捕获(无算法异常nsa)
{
Log.d(“异常”,“无算法”);
Assert.assertTrue(false);
}
}
}捕获(PackageManager.NameNotFoundException nnfe)
{
Log.d(“异常”,“未找到名称”);
Assert.assertNull(“未找到名称”,nnfe);
}
}
已按下公共无效PostButton(视图)
{
Toast.makeText(这是“共享到Facebook”,Toast.LENGTH_SHORT.show();
mPendingAction=true;
Session=Session.getActiveSession();
if(会话==null){
会话=新会话(getApplicationContext());
@抑制警告(“未使用”)
Session.OpenRequest openSessionRequest=新建Session.OpenRequest(此);
}
其他的
{
if(session.getState().equals(SessionState.CREATED))
{
//会话未打开或关闭,会话已创建但未打开。
会话=新会话(本);
Session.setActiveSession(Session);
session.openForPublish(newsession.OpenRequest(this).setCallback(callback).setPermissions(PERMISSION));
}
其他的
{
onSessionStateChange(会话,session.getState(),null);
}
}
Session.setActiveSession(Session);
}
private void OnSessionState更改(会话、会话状态、异常)
{
if(异常!=null)
{
//在这里处理异常。
Log.v(“Facebook回调”、“Facebook登录错误”+异常);
返回;
}
if(state!=null&&state.isOpened()){
if(会话.isPermission已授予(权限))
{
if(mPendingAction)
{
//会话已准备好发出请求。
postImageToFacebook();
mPendingAction=false;
}
}
其他的
{
//如果我们没有权限,请获取权限。
试一试{
session.requestNewPublishPermissions(newsession.NewPermissionsRequest(this,PERMISSION));
}捕获(例外e){
Toast.makeText(getApplicationContext(),“发布拒绝访问”,Toast.LENGTH_LONG.show();
}
}
}
else if(state.isClosed())
{
//会话已注销。
返回;
}
}
私有无效postImageToFacebook(){
Session=Session.getActiveSession();
final Uri=(Uri)mExtras.get(Intent.EXTRA_-STREAM);
最终字符串extraText=mPostTextView.getText().toString();
if(session.ispermissiongrated(“发布操作”))
{
Bundle param=新Bundle();
//添加图像
试一试{
位图Bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
ByteArrayOutputStream=新建ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,100,流);
字节[]byteArrayData=stream.toByteArray();
参数putByteArray(“图片”,byteArrayData);
}捕获(ioe异常ioe){
//发送的图像现在不在那里?
Assert.assertTrue(false);
}
//添加标题
参数putString(“消息”,extraText);
Request Request=new Request(会话,“me/photos”,参数,HttpMethod.POST,new Request.Callback(){
@凌驾
未完成公共无效(响应){
addNotification(getString(R.string.photo_post)、response.getGraphObject()、response.getError());
}
},空);
RequestAsyncTask asyncTask=新的RequestAsyncTask(请求);
asyncTask.execute();