向片段请求新的发布权限

时间:2013-12-11 11:26:49

标签: android facebook android-fragments

如果他不这样做,我需要向用户询问是否授权发布权限。 我用这行代码做到了:

//Into ShareOnFacebookFragment
Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));

SocialSharingActivity是与我的片段相关的活动(ShareOnFacebookFragment)。 当我运行应用程序时,应用程序正确地问我发布权限,我接受,但是当我发布时,我的logcat中出现了这个错误:

12-11 12:17:27.277: E/AndroidRuntime(29125): Caused by: java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.

老实说,我唯一的想法是requestNewPublishPermissions在后台运行Async,然后当我尝试发布时遇到问题。我怎么能解决这个问题?我也发布了我的整个片段代码

    private final String TAG = "ShareFragment";

private UiLifecycleHelper uiHelper;
//   To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the
//   Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in
//   order to communicate with the Activity.

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

private void onSessionStateChange(Session session, SessionState state,Exception exception) {
   Log.i("CALLBACK: ", "Session state change: "+state);

   }


   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);

       }
   @Override 
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   uiHelper = new UiLifecycleHelper(getActivity(), callback);
   uiHelper.onCreate(savedInstanceState);
   };
// This makes sure that the container activity has implemented
   // the callback interface. If not, it throws an exception
//   try {
//       mCallback = (OnHeadlineSelectedListener) activity;
//   } catch (ClassCastException e) {
//       throw new ClassCastException(activity.toString()
//               + " must implement OnHeadlineSelectedListener");
//   }
//}
  @Override
   public void onPause() {
     super.onPause();
     uiHelper.onPause();
  };
   @Override
      public void onResume() {
         // TODO Auto-generated method stub
         super.onResume();
         uiHelper.onResume();
      }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState) {
       // Inflate the layout for this fragment
      RelativeLayout myRelative =  (RelativeLayout) inflater.inflate(R.layout.share_frame, container, false);
      shareButton = (Button) myRelative.findViewById(R.id.shareButton);
      workoutIdTextView = (TextView) myRelative.findViewById(R.id.workoutIdTextView);
      objectCreatedTextView = (TextView) myRelative.findViewById(R.id.objectCreatedTextView);
      actionCreatedTextView = (TextView) myRelative.findViewById(R.id.actionCreatedTextView);


       return myRelative;
   }

   @Override
      public void onSaveInstanceState(Bundle outState) {
         // TODO Auto-generated method stub
         super.onSaveInstanceState(outState);
         uiHelper.onSaveInstanceState(outState);
      }

   @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
         // TODO Auto-generated method stub
         super.onActivityResult(requestCode, resultCode, data);
         uiHelper.onActivityResult(requestCode, resultCode, data);

      }
   @Override
      public void onDestroy() {
         // TODO Auto-generated method stub
         super.onDestroy();
         uiHelper.onDestroy();
      }
   @Override
      public void onStart() {
         // TODO Auto-generated method stub
         super.onStart();

      }
   @Override
   public void onActivityCreated(Bundle bundle) {
      super.onActivityCreated(bundle);
      Log.i(TAG, "ONACTIVITYCREATED");
      SocialSharingActivity caller =(SocialSharingActivity) getActivity();
      Log.w(TAG, "caller "+caller.toString());
      workoutIdTextView.setText(String.valueOf(caller.getWorkoutId()));
      Log.i(TAG, "Data course " + caller.getEwCourse().toString());
      Log.i(TAG, "Message Run " + caller.getEwRun().toString());
      ewCourseFrag = caller.getEwCourse();
      ewRunFrag = caller.getEwRun();



      parAct=new Bundle();
      parAct.putAll(ewRunFrag.getParams());
      parObj = new Bundle();
      parObj.putString("access_token", APP_ACCESS_TOKEN);      
      gson = new Gson();
      parObj.putString("object", gson.toJson(ewCourseFrag));
      publishSession = Session.getActiveSession();
      //------------------------------Batch HTTP request-----------------------------------------------------------------------------------------------------------------
      // 
      //------------------------------Declaration--and--implementation--of--Callback-----------------------------------------------------------------------------------------------------------------
      RequestBatch.Callback batchCallback= new RequestBatch.Callback() {

         @Override
         public void onBatchCompleted(RequestBatch batch) {
            Log.w(TAG, "Batch completed: "+ "OK");

            //
         }
      };
      //
      Request.Callback reqCreateObjCallback= new Request.Callback() {

         @Override
         public void onCompleted(Response response) {


            if(response.getError() == null){
               Log.w(TAG,"reqCreateObjCallback: "+ "OK");
               objectCreatedTextView.setText("OK object");

            }
            else {
               Log.e(TAG,"reqCreateObjCallback: "+ response.getError().toString());
               Log.d(TAG, response.getError().getCategory().toString());
               objectCreatedTextView.setText(response.getError().getCategory().toString());
            }
            //400

         }

      };
      //
      Request.Callback reqPublishCallback= new Request.Callback() {

         @Override
         public void onCompleted(Response response) {


            if(response.getError() == null) {
               Log.w(TAG, "reqPublishCallback: "+ "OK");
               actionCreatedTextView.setText("OK action");

               //                   Toast.makeText(context, "ACTION_CREATED", Toast.LENGTH_LONG).show();
            }
            else {
               Log.e(TAG, "reqPublishCallback: "+ response.getError().toString());
               Log.d(TAG, response.getError().getCategory().toString());
               actionCreatedTextView.setText(response.getError().getCategory().toString());
            }
         }

      };
      //-----------------------------------------------------------------------------------------------------------------------------------------------------------------

      //------------------------------Create--instance--of--RequestBatch--------------------------------------------------------------------------------------------------------
      RequestBatch requestBatch= new RequestBatch();

      //------------------------------Request--for-create-the-graph-object---------------------------------------------------------------------------------------------------------------
      Request reqCreateObj= new Request(
            publishSession,  
            "app/objects/fitness.course", 
            parObj,HttpMethod.POST);                    //Create a Request for a common ObiectGraph of type course
      reqCreateObj.setCallback(reqCreateObjCallback);       //Set the callback for the Request
      reqCreateObj.setBatchEntryName("objectCreate");     //Tag the request name into the Batch with "objectCreate"
      requestBatch.add(reqCreateObj);                   //Add the request to the batch

      //------------------------------Request-for-publish-action-------------------------------------------------------------------------------------------------------------------------------
      parAct.putString("course",
            "{result=objectCreate:$.id}");                 //Use the tag to retrieve the informations about the graph object created

      //can also add scrape flag to update the object
      //        par2.putString("end_time", new Date(new Date().getTime()+1000*60*2).toString()); // live text test
      Request reqPublish = 
            new Request(publishSession,        //Create a request for publish an action relative to the object;
                  // Similarly at a  phrase, an action is like "verbo", graph object
                  "me/fitness.runs/",parAct,              //is like "complemento oggetto" and the the user is "soggetto"
                  HttpMethod.POST);                      //
      reqPublish.setCallback(reqPublishCallback);            //Set the callback for the Request
      requestBatch.add(reqPublish);                          //Add the request to the batch
      requestBatch.addCallback(batchCallback);               //Set the callback for the Batch Request
      //Check network session opened and permissions
      //codice sospeso
      if(Session.getActiveSession().isOpened() && hasPublishPermission() && isNetworkAvailable()) {
         Toast.makeText(getActivity(), "Session is opened, I have permission, Network is On", Toast.LENGTH_LONG).show();
         requestBatch.executeAsync();
      }
      else if (Session.getActiveSession().isOpened() && isNetworkAvailable()){
         Toast.makeText(getActivity(), "I dont have Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
         Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));
         Toast.makeText(getActivity(), "Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
      }
      else if (Session.getActiveSession().isOpened() && hasPublishPermission()) {
         Toast.makeText(getActivity(), "Check your status connection.", Toast.LENGTH_LONG).show();


      }

      else {
         Intent loginIntent = new Intent((SocialSharingActivity)getActivity(),FbLoginActivity.class);
         startActivity(loginIntent);

      }



   }



     private boolean isNetworkAvailable() {  
          ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);  
          NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();  
          return activeNetworkInfo != null;  
      } 

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


    }

0 个答案:

没有答案