如何使用facebook sdk for android公开应用程序?

时间:2014-09-05 20:45:04

标签: java android facebook facebook-graph-api facebook-android-sdk

这是我的代码......

public class FacebookShare extends FragmentActivity {

    private static final String TAG = "FacebookShare";
    private static final String PERMISSION = "publish_actions";
    public  static final String PACKAGE = "com.facebook.katana";
    private final String PENDING_ACTION_BUNDLE_KEY = "com.myapp.mypackage.facebook.facebookshare:PendingAction";

    private FragmentActivity mActivity;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;
    private boolean canPresentShareDialogWithPhotos;
    private String mTitle, mDescription, mUrlShare, mUrlImg;

    private enum PendingAction {
        NONE,
        POST_PHOTO,
        POST_STATUS_UPDATE
    }
    private UiLifecycleHelper uiHelper;

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

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.d("HelloFacebook", "Success!");
        }
    };

    public FacebookShare(FragmentActivity act, String applicationId, String title, String description, String urlShare, String urlImg) {
        mActivity = act;
        mTitle = title;
        mDescription = description;
        mUrlShare = urlShare;
        mUrlImg = urlImg;

        uiHelper = new UiLifecycleHelper(mActivity, callback, applicationId);
        uiHelper.onCreate(new Bundle());

        canPresentShareDialog = FacebookDialog.canPresentShareDialog(mActivity,
                FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
        canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(mActivity,
                FacebookDialog.ShareDialogFeature.PHOTOS);
    }

    public static void showDialog(FragmentActivity act){
        try{
            Intent waIntent = new Intent(Intent.ACTION_SEND);
            waIntent.setPackage(WhatsApp.PACKAGE);
            act.startActivity(Intent.createChooser(waIntent, "Facebook no se encuentra instalado."));
        }catch(Exception e){                    
            Toast.makeText(act, "Facebook no se encuentra instalado.", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        AppEventsLogger.activateApp(this);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);

        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

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

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

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (pendingAction != PendingAction.NONE &&
                (exception instanceof FacebookOperationCanceledException ||
                        exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(FacebookShare.this)
            .setTitle(R.string.cancelled)
            .setMessage(R.string.permission_not_granted)
            .setPositiveButton(R.string.ok, null)
            .show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        pendingAction = PendingAction.NONE;
        if(Session.getActiveSession() != null){
            switch (previouslyPendingAction) {
            case POST_PHOTO:
                postPhoto();
                break;
            case POST_STATUS_UPDATE:
                postStatusUpdate();
                break;
            }
        }else{
            Session.openActiveSession(mActivity, true, new Session.StatusCallback() {
                @SuppressWarnings("deprecation")
                @Override
                public void call(Session session, SessionState state, Exception exception) {
                    if (session.isOpened()) {

                        Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                            @Override
                            public void onCompleted(GraphUser mUser, Response response) {
                                if (user != null) {
                                    FacebookShare.this.user = mUser;
                                }
                            }
                        });

                    }
                }
            });
        }
    }

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

    private void showPublishResult(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();
        }

        new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(alertMessage)
        .setPositiveButton(R.string.ok, null)
        .show();
    }

    public void onClickPostStatusUpdate() {
        performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
    }

    public void onClickPostPhoto() {
        performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
    }

    private FacebookDialog.PhotoShareDialogBuilder createShareDialogBuilderForPhoto(Bitmap... photos) {
        return new FacebookDialog.PhotoShareDialogBuilder(mActivity)
        .addPhotos(Arrays.asList(photos));
    }

    private void postPhoto() { 
        AsyncTaskGR.runParallelAsyncTask(new AsyncTask<Object, Bitmap, Bitmap>(){
            @Override
            protected Bitmap doInBackground(Object... params) {
                Bitmap image = getBitmapFromURL(mUrlImg);
                return image;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                if (canPresentShareDialogWithPhotos) {
                    FacebookDialog shareDialog = createShareDialogBuilderForPhoto(result).build();
                    uiHelper.trackPendingDialogCall(shareDialog.present());
                } else if (hasPublishPermission()) {
                    Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), result, new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
                        }
                    });
                    request.executeAsync();
                } else {
                    pendingAction = PendingAction.POST_PHOTO;
                }
            }
        });
    }

    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(mActivity)
        .setName(mTitle)
        .setDescription(mDescription)
        .setLink(mUrlShare);
    }
    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    showPublishResult(message, response.getGraphObject(), response.getError());
                }
            });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(mActivity, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }
    private static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            Log.e(TAG, "getBitmapFromURL(): " + e.getMessage());
            return null;
        }
    }
}

这就是我称呼它的方式......

public static void send(FragmentActivity act, String applicationId, String title, String description, String urlShare, String urlImg) {
        if(Utilities.isPackageInstalled(FacebookShare.PACKAGE, act)){
            if(Util.isOnline(act)){
                FacebookShare fb = new FacebookShare(act, applicationId, title, description, urlShare, urlImg);
                if(Utilities.isNullorEmpty(urlImg)){
                    fb.onClickPostStatusUpdate();
                }else{
                    fb.onClickPostPhoto();
                }
            }
        }else{
            FacebookShare.showDialog(act);
        }
    }

这可以使用我的帐户,但如果我使用另一个不让我发布,并尝试设置权限&#34; publish_actions&#34;在网页上的mi配置文件但不要让我... ps:填写所有需要的字段

有什么建议吗? ......谢谢!

logcat不显示任何错误......

0 个答案:

没有答案