2
import com.beta.wow.SessionManager;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;

public class Promodetails extends Activity
{   

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager sessionwow;
// Button Logout
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private Session currentSession;
public String sessionemail;
ImageButton imgrvw,imgmap,imgshare;
OpenRequest open = new OpenRequest(this);

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    //No title bar will be shown
    requestWindowFeature(Window.FEATURE_NO_TITLE);      
    setContentView(R.layout.promodetails);

    // Session class instance
    sessionwow = new SessionManager(getApplicationContext());
    Toast.makeText(getApplicationContext(), "User Login Status: " +   sessionwow.isLoggedIn(), Toast.LENGTH_LONG).show();
    /**
     * Call this function whenever you want to check user login
     * This will redirect user to LoginActivity is he is not
     * logged in
     * */
    sessionwow.checkLogin();

    // get user data from session
    HashMap<String, String> user = sessionwow.getUserDetails();
    // email
    sessionemail = user.get(SessionManager.KEY_EMAIL);

    //***************************
    currentSession=Session.getActiveSession();
     if (currentSession == null) 
     {
            if (savedInstanceState != null) 
            {
                currentSession = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }

            Session.setActiveSession(currentSession);
            if (currentSession.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                currentSession.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
     }


    imgshare=(ImageButton)findViewById(R.id.imageshare);

    imgshare.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub

            //login.setVisibility(View.GONE);


             if (currentSession == null)
             {
               connectToFB();
             }
             else if(currentSession != null && currentSession.isOpened())
             {
                  List<String> permissions = new ArrayList<String>();
                  permissions.add("publish_stream");
                  open.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
                  open.setPermissions(permissions);
                  open.setCallback(statusCallback);
                  currentSession.openForPublish(open);
             }

            //logout.setVisibility(View.VISIBLE);
           // publishButton.setVisibility(View.VISIBLE);
           // publishStory();

            }
        });


}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 //FB ADD on
    super.onActivityResult(requestCode, resultCode, data);
     if (currentSession != null) 
     {
           currentSession.onActivityResult(this, requestCode, resultCode, data);
     }

    switch (requestCode) {
    case (15):
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();

                if (uri != null) {
                    Cursor c = null;
                    try {
                        c = getContentResolver()
                                .query(uri,
                                        new String[] {
                                                ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                ContactsContract.CommonDataKinds.Phone.TYPE },
                                        null, null, null);

                        if (c != null && c.moveToFirst()) {
                            String number = c.getString(0);
                            tvphoneno.setText(number);
                        }
                    } finally {
                        if (c != null) {
                            c.close();
                        }
                    }
                }
            }
        } else {
            Toast.makeText(Promodetails.this, "No phone number picked",
                    Toast.LENGTH_LONG).show();
        }
    }
}


  /**
  * this method is used by the facebook API
  */


   /**
  * manages the session state change. This method is called after the
  * <code>connectToFB</code> method.
  * 
  * @param session
  * @param state
  * @param exception
  */
  private void onSessionStateChange(Session session, SessionState state,
   Exception exception) {
  if (session != currentSession) {
   return;
  }

  if (state.isOpened()) {
   // Log in just happened.
   Toast.makeText(getApplicationContext(), "session opened",
     Toast.LENGTH_SHORT).show();

   publishStory();
  } else if (state.isClosed()) {
   // Log out just happened. Update the UI.
   Toast.makeText(getApplicationContext(), "session closed",
     Toast.LENGTH_SHORT).show();
    }
   }

 /**
  * Publishes story on the logged user's wall
  */
 public void publishStory() {
  Bundle params = new Bundle();
    String t1=tvdealname.getText().toString();
    String t2=tvdiscpercent.getText().toString();
    String t3=tvstore.getText().toString();
    //String t4=tvlocation.getText().toString();
    String t5=tvaddress1.getText().toString();
    String t6=tvaddress2.getText().toString();
    Bundle bdl = getIntent().getExtras();
    String sharepicture=bdl.getString("SHARE");
    //String t7=tvstore.getText().toString();
    String desc="Wow Today's deal on "+ t1 + "-" + t2 + "off now on " + t1 + "only at "+   t3 + ", " + t5 + "," + t6 + ".";
  params.putString("name", "Check out the #WoW deal from " + t3 + ".");
  params.putString("caption", "Download #WoW now only Google play store");
  params.putString("description",desc);
  params.putString("link", "https://play.google.com/store/apps/details?id=com.rovio.angrybirdsrio&hl=en");
  params.putString("picture",sharepicture);

  WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this,currentSession, params)).setOnCompleteListener(new OnCompleteListener() {

     @Override
     public void onComplete(Bundle values,
       FacebookException error) {
      if (error == null) {
       // When the story is posted, echo the success
       // and the post Id.
       final String postId = values.getString("post_id");
       if (postId != null) 
       {
           Toast.makeText(getApplicationContext(),"Promo shared on Facebook successfully",Toast.LENGTH_SHORT).show();
       } 
       else 
       {
        // User clicked the Cancel button
        Toast.makeText(getApplicationContext(),
          "Publish cancelled", Toast.LENGTH_SHORT).show();
       }
      } else if (error instanceof FacebookOperationCanceledException) {
       // User clicked the "x" button
       Toast.makeText(getApplicationContext(),
         "Publish cancelled", Toast.LENGTH_SHORT)
         .show();
      } else {
       // Generic, ex: network error
       Toast.makeText(getApplicationContext(),
         "Error posting story", Toast.LENGTH_SHORT)
         .show();
      }
     }

    }).setFrom("").build();
  feedDialog.show();

 }

 public void connectToFB() {

      List<String> permissions = new ArrayList<String>();
      permissions.add("publish_stream");
      currentSession = new Session.Builder(this).build();
      currentSession.addCallback(statusCallback);
      Session.OpenRequest openRequest = new Session.OpenRequest(Promodetails.this);
      openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
      openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
      openRequest.setPermissions(permissions);
      currentSession.openForPublish(openRequest);
     }

 @Override
    public void onBackPressed() 
 {
        // Write your code here
        Intent intent = new Intent(Promodetails.this,MainActivity.class);
        startActivity(intent);
        Toast.makeText(Promodetails.this, "Back button pressed",  Toast.LENGTH_LONG).show();
        super.onBackPressed();

 }


@Override
public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
}

private class SessionStatusCallback implements Session.StatusCallback {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        //updateView();
    }
}

}

私はアンドロイド開発に不慣れです。フェイスブックSDKも!問題は、アプリにfbオプションでログインがあることです。これでセッションが作成され、ログインに成功し、アクセス トークンとともにユーザーの詳細を取得できるようになりました。しかし、アプリにログインした後、いくつかのコンテンツを共有する必要があります。

そのため、ユーザーが Facebook でコンテンツを直接共有できるように、Facebook のアクティブなセッションをキャッチする必要があります。

コードを実行しましたが、このエラーが表示されます。誰かが抜け穴から私を助けることができますか?

ありがとう:)表示されているlogcatにエラーを貼り付けています。

 07-08 07:17:16.249: E/AndroidRuntime(2045): FATAL EXCEPTION: main
 07-08 07:17:16.249: E/AndroidRuntime(2045): java.lang.UnsupportedOperationException:      Session: an attempt was made to open an already opened session.
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at     com.facebook.Session.open(Session.java:1223)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at com.facebook.Session.openForPublish(Session.java:519)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at com.beta.wow.Promodetails$1.onClick(Promodetails.java:123)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.view.View.performClick(View.java:4240)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.view.View$PerformClick.run(View.java:17721)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.os.Handler.handleCallback(Handler.java:730)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.os.Handler.dispatchMessage(Handler.java:92)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.os.Looper.loop(Looper.java:137)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at android.app.ActivityThread.main(ActivityThread.java:5103)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at java.lang.reflect.Method.invokeNative(Native Method)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at java.lang.reflect.Method.invoke(Method.java:525)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 07-08 07:17:16.249: E/AndroidRuntime(2045):    at dalvik.system.NativeStart.main(Native Method)
4

0 に答える 0