2016-11-25 26 views
0

我使用火力的UI與Twitter登錄,現在作爲文檔說我得使用方法private void handleTwitterSession(TwitterSession session)訪問令牌。登錄工作正常,但我不知道發送給該功能的所謂的「會話」的內容。我如何從FirebaseAuth毛特對象??訪問令牌......非常感謝你。到文檔的鏈接是這個https://firebase.google.com/docs/auth/android/twitter-loginTwitter的API:我如何獲得嘰嘰喳喳的accessToken張貼在代表用戶的?我已經登錄成功

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "NearGoal"; 

    private Toolbar toolbar; 
    private TabLayout tabLayout; 
    private ViewPager viewPager; 

    private List<causes> causesList = new ArrayList<>(); 
    private List<FundItem> fundItemList = new ArrayList<>(); 
    private RecyclerView rv; 
    private RecyclerView rvgoal; 
    private causes_adaptor cAdapter; 
    private causes_adaptor_near_goal gAdapter; 
    private ProgressBar pb; 
    private ProgressBar progressBarGral; 
    private Context mContext; 
    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener mAuthListener; 


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

     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 

     mAuth = FirebaseAuth.getInstance(); 
     if (mAuth.getCurrentUser() != null) { 
      // already signed in 
      FirebaseUser firebaseUser=mAuth.getCurrentUser(); 
      Log.d("TWITTER_USER_INFO",""+mAuth.getCurrentUser().getToken(true)); 
     } else { 
      startActivityForResult(
        AuthUI.getInstance() 
          .createSignInIntentBuilder() 
          .setProviders(Arrays.asList(
            new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build())) 
          .build(), 
        RC_SIGN_IN); 
     } 
//TwitterAuthProvider 
     Fresco.initialize(getApplication()); 

     setContentView(R.layout.activity_main); 

     rv = (RecyclerView) findViewById(R.id.rv); 
     rvgoal = (RecyclerView) findViewById(R.id.rvgoal); 


     RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
     rv.setLayoutManager(mLayoutManager); 
     rv.setItemAnimator(new DefaultItemAnimator()); 

     RecyclerView.LayoutManager gLayoutManager =new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); 
     rvgoal.setLayoutManager(gLayoutManager); 
     rvgoal.setDrawingCacheEnabled(true); 
     rvgoal.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); 
     rvgoal.setItemAnimator(new DefaultItemAnimator()); 


     toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     toolbar.setTitle("Your Title"); 
     //toolbar.setTitleTextColor(getResources().getColor(android.R.color.transparent)); 

     getSupportActionBar().setDisplayHomeAsUpEnabled(false); 


     //tabLayout = (TabLayout) findViewById(R.id.tabs); 
     //tabLayout.setupWithViewPager(viewPager); 
     //collapsingToolbarLayout.setTitle(" "); 


     pb=(ProgressBar) findViewById(R.id.ProgressBar); 

     progressBarGral = (ProgressBar) findViewById(R.id.progress_bar); 

     // String url = "http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/"; 
     new DownloadTask().execute();; 

     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in 
        Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); 
       } else { 
        // User is signed out 
        Log.d(TAG, "onAuthStateChanged:signed_out"); 
       } 
      } 
     }; 

    } 
    public class DownloadTask extends AsyncTask<String, Void, Integer> { 

     URL url = null; 

     @Override 
     protected void onPreExecute() { 
      progressBarGral.setVisibility(View.VISIBLE); 
     } 
     @Override 
     protected Integer doInBackground(String... params) { 
      Integer result = 0; 
      HttpURLConnection urlConnection; 
      try { 
       url = new URL(getResources().getString(R.string.backend_base_url)+"/api/campaigns/get/all/"); 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       int statusCode = urlConnection.getResponseCode(); 

       // 200 represents HTTP OK 
       if (statusCode == 200) { 
        BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
        StringBuilder response = new StringBuilder(); 
        String line; 
        while ((line = r.readLine()) != null) { 
         response.append(line); 
        } 
        parseResult(response.toString()); 
        result = 1; // Successful 
       } else { 
        result = 0; //"Failed to fetch data!"; 
       } 
      } catch (Exception e) { 
       Log.d(TAG, e.getLocalizedMessage()); 
      } 
      return result; //"Failed to fetch data!"; 
     } 
     @Override 
     protected void onPostExecute(Integer result) { 
      progressBarGral.setVisibility(View.GONE); 

      if (result == 1) { 
       gAdapter = new causes_adaptor_near_goal(MainActivity.this, causesList); 
       //gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList); 
       rvgoal.setAdapter(gAdapter); 

       cAdapter = new causes_adaptor(MainActivity.this, causesList); 
       //gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList); 
       rv.setAdapter(cAdapter); 
      } else { 
       Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show(); 
      } 
     } 
     private void parseResult(String result) { 
      try { 
       JSONObject response = new JSONObject(result); 
       JSONArray posts = response.getJSONArray("rows"); 
       causesList = new ArrayList<>(); 

       JSONArray funds; 

       for (int i = 0; i < posts.length(); i++) { 
        fundItemList = new ArrayList<>(); 
        JSONObject post = posts.optJSONObject(i); 
        funds = post.getJSONArray("foundations"); 

        causes item = new causes(); 
        item.setName(post.optString("name")); 
        item.setcause_description(post.optString("cause_description")); 
        item.setGoal(post.optString("goal")); 
        item.setCurrent_contributions(post.optString("current_contributions")); 
        item.setTotalUniqueUsersReached(post.optString("totalUniqueUsersReached")); 
        item.setState(post.optString("state")); 
        item.setId(post.optString("_id")); 
        item.setRemaining_ammount_to_goal(post.optString("remaining_ammount_to_goal")); 
        item.setGoal_percentage_achieved(post.optString("goal_percentage_achieved")); 
        item.setCampaign_ending_date(post.optString("campaign_ending_date")); 




        for(int k=0, len=funds.length(); k <len;k++) { 
        FundItem fundItem = new FundItem(); 
        JSONObject fund = funds.optJSONObject(k); 

         fundItem.setTwitter_account(fund.getString("twitter_account")); 
         fundItem.setName(fund.getString("name")); 
         fundItem.setPic_path(fund.getString("pic_path")); 

        fundItemList.add(fundItem); 
        } 
         item.setFundlist(fundItemList); 
        causesList.add(item); 
      } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
    } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu_home, menu); 
     return true; 
    } 


    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_OK) { 
      // user is signed in! 
      Log.d("user_status","user signed in!!"); 
      return; 
     } 

     // Sign in canceled 
     if (resultCode == RESULT_CANCELED) { 
      /* startActivityForResult(
        AuthUI.getInstance() 
          .createSignInIntentBuilder() 
          .setProviders(Arrays.asList(
            new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build())) 
          .build(), 
        RC_SIGN_IN);*/ 
      return; 
     } 

     // User is not signed in. Maybe just wait for the user to press 
     // "sign in" again, or show a message. 
    } 


    private void handleTwitterSession(TwitterSession session) { 
     Log.d(TAG, "handleTwitterSession:" + session); 

     AuthCredential credential = TwitterAuthProvider.getCredential(
       session.getAuthToken().token, 
       session.getAuthToken().secret); 

     mAuth.signInWithCredential(credential) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); 

         // If sign in fails, display a message to the user. If sign in succeeds 
         // the auth state listener will be notified and logic to handle the 
         // signed in user can be handled in the listener. 
         if (!task.isSuccessful()) { 
          Log.w(TAG, "signInWithCredential", task.getException()); 
          Toast.makeText(getApplicationContext(), "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
         } 
        } 
       }); 
    } 



    @Override 
    public void onStart() { 
     super.onStart(); 
     mAuth.addAuthStateListener(mAuthListener); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 
     if (mAuthListener != null) { 
      mAuth.removeAuthStateListener(mAuthListener); 
     } 
    } 




} 

回答

0

我解決它通過使用火力UI onActivityResult參數數據,而不是嘗試使用handleTwitterSession功能,導致火力的UI已經處理該loginWithCredentials所以這將是多餘.....改變onActivityResult是什麼讓差異在這種情況下,我張貼工作代碼以供將來參考:

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) { 
      IdpResponse response = IdpResponse.fromResultIntent(data); 
      //twitter token 
      response.getIdpToken(); 
      //twitter secret 
      response.getIdpSecret(); 
     } 
    } 
0

您可以使用setCallBack()得到TwitterSession

mLoginButton.setCallback(new Callback<TwitterSession>() { 
    @Override 
    public void success(Result<TwitterSession> result) { 
     Log.d(TAG, "twitterLogin:success" + result); 
     handleTwitterSession(result.data); 
    } 

    @Override 
    public void failure(TwitterException exception) { 
     Log.w(TAG, "twitterLogin:failure", exception); 
    } 
}); 

看看this問題也。

+0

我沒有mLoginButton ...我正在使用firebase-UI活動登錄並返回到上面發佈的代碼.... .startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setProviders(Arrays.asList( 新AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build())) .build(), RC_SIGN_IN);這是去的情況下,用戶是不是當他們進入的主要活動登錄的登錄活動的一部分 – Juan