简体   繁体   English

Facebook上的Android分享(SDK 4)

[英]Android Sharing on Facebook (SDK 4)

Trying to share an image with Facebook SDK 4.0 for android. 尝试与Facebook SDK 4.0 for android共享图像。

app.graddle app.graddle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    // Facebook's library to implement Login with Facebook
    compile 'com.facebook.android:facebook-android-sdk:4.0.1'
}

AndroidManifest.xml AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.facebookshare" >
    <uses-permission android:name="android.permission.INTERNET" />    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.facebook.FacebookActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

        <provider android:authorities="com.facebook.app.FacebookContentProvider1234"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true"/>

    </application>

</manifest>

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int ACTION_PICK_IMAGE = 1;

    //Facebook client
    private CallbackManager fb_callbackManager;
    private ShareDialog fb_shareDialog;

    private Button button;
    private ImageView imageView;
    private EditText editText;

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

        // Initialize Facebook API
        FacebookSdk.sdkInitialize(getApplicationContext());
        fb_callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setOnClickListener(this);

        editText = (EditText) findViewById(R.id.editText);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @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) {
        int id = item.getItemId();

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

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.imageView:
                loadImage();
                break;
            case R.id.button:
                share();
                break;
        }
    }

    private void loadImage(){
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        photoPickerIntent.putExtra("crop", "true");
        photoPickerIntent.putExtra("scale", true);
        photoPickerIntent.putExtra("scaleUpIfNeeded", true);
        photoPickerIntent.putExtra("max-width", 170);
        photoPickerIntent.putExtra("max-height", 160);
        photoPickerIntent.putExtra("aspectX", 1);
        photoPickerIntent.putExtra("aspectY",1);

        startActivityForResult(photoPickerIntent, ACTION_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ACTION_PICK_IMAGE) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                //get the cropped bitmap
                Bitmap thePic = extras.getParcelable("data");
                imageView.setImageBitmap(thePic);
            }
        }
    }

    protected void share(){
        String shareText = editText.getText().toString();
        ShareDialog shareDialog = new ShareDialog(this);
        if (ShareDialog.canShow(SharePhotoContent.class)) {
            shareDialog.registerCallback(fb_callbackManager, new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    Toast.makeText(MainActivity.this, "Share Success", Toast.LENGTH_SHORT).show();
                    Log.d("DEBUG", "SHARE SUCCESS");
                }

                @Override
                public void onCancel() {
                    Toast.makeText(MainActivity.this, "Share Cancelled", Toast.LENGTH_SHORT).show();
                    Log.d("DEBUG", "SHARE CACELLED");
                }

                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e("DEBUG", "Share: " + exception.getMessage());
                    exception.printStackTrace();
                }
            });

            SharePhoto photo = new SharePhoto.Builder()
                    .setBitmap(((BitmapDrawable) imageView.getDrawable()).getBitmap())
                    .build();
            SharePhotoContent content = new SharePhotoContent.Builder()
                    .addPhoto(photo)
                    .build();

            shareDialog.show(content);
        }

    }
}

Nothing is shown, or at least not visible, because I have to hit back to be able to interact with my activity again after trying to share on Facebook. 没有显示任何内容,或者至少不可见,因为在尝试在Facebook上分享后,我必须回击以便能够再次与我的活动进行交互。

No DEBUG string is logged on Logcat. 在Logcat上没有记录DEBUG字符串。 So I understand ShareDialog can show Photo content. 所以我理解ShareDialog可以显示照片内容。

Could somebody post a simple working example of sharing image with Facebook for SDK 4.0(android)? 有人可以发布一个简单的工作示例,与Facebook for SDK 4.0(android)共享图像?

You need to add an Internet Permission to your android manifest for sharing to work! 您需要为您的Android清单添加Internet权限才能共享工作!

<manifest xlmns:android...>
    ...
    <uses-permission android:name="android.permission.INTERNET" />
    <application ...
</manifest>

EDIT 编辑

public class MainActivity extends AppCompatActivity {

    private CallbackManager callbackManager;
    private LoginManager manager;

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

        FacebookSdk.sdkInitialize(getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        List<String> permissionNeeds = Arrays.asList("publish_actions");

        manager = LoginManager.getInstance();

        manager.logInWithPublishPermissions(this, permissionNeeds);

        manager.registerCallback(callbackManager, new  FacebookCallback<LoginResult>()
       {
            @Override
            public void onSuccess(LoginResult loginResult)
            {
                publishImage();
            }

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

            @Override
            public void onError(FacebookException exception)
            {
                System.out.println("onError");
            }
        });
     }

     private void publishImage(){
         Bitmap image = BitmapFactory.decodeResource(getResources(),     R.mipmap.ic_launcher);

         SharePhoto photo = new SharePhoto.Builder()
            .setBitmap(image)
            .setCaption("Welcome To Facebook Photo Sharing on steroids!")
            .build();

         SharePhotoContent content = new SharePhotoContent.Builder()
            .addPhoto(photo)
            .build();

         ShareApi.share(content, null);

    }

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

This piece of code posts an image to Facebook wall. 这段代码将图像发布到Facebook墙上。 The thing you might want to do is use the share dialog; 您可能想要做的是使用共享对话框; here I just share the image directly with a caption without using the share dialog. 在这里,我只是直接与标题共享图像,而不使用共享对话框。

Please let me know what you get! 请让我知道你得到了什么! I have tested it to make sure it works. 我测试过它以确保它有效。

If you're sharing links, images or video via the Facebook for Android app, you also need to declare the FacebookContentProvider in the manifest , like: 如果您通过Facebook for Android应用程序共享链接,图像或视频,您还需要在清单中声明FacebookContentProvider ,例如:

<provider android:authorities="com.facebook.app.FacebookContentProvider1234"
          android:name="com.facebook.FacebookContentProvider"
          android:exported="true" />

In above line # 1 you will see a number 1234, in FacebookContentProvider1234 , you need to replace it with your Facebook app Id. 在上面的第1行中,您将看到一个数字1234,在FacebookContentProvider1234 ,您需要将其替换为您的Facebook应用ID。

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

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