Java 使用Firebase的TwitterAPI:如何让Twitter accessToken在用户';代表谁??我已成功登录

Java 使用Firebase的TwitterAPI:如何让Twitter accessToken在用户';代表谁??我已成功登录,java,android,twitter-oauth,firebaseui,twitter-login,Java,Android,Twitter Oauth,Firebaseui,Twitter Login,我正在使用firebase UI登录twitter,现在正如文档所说,我必须使用方法private void handleTwitterSession(TwitterSession会话)获取访问令牌。登录工作正常,但我不知道向该功能发送什么,即所谓的“会话”。如何从FirebaseAuth mAuth对象获取访问令牌???…非常感谢。指向文档的链接如下所示 public类MainActivity扩展了AppCompatActivity{ 私有静态最终字符串TAG=“NearGoal”; 专用工具

我正在使用firebase UI登录twitter,现在正如文档所说,我必须使用方法
private void handleTwitterSession(TwitterSession会话)
获取访问令牌。登录工作正常,但我不知道向该功能发送什么,即所谓的“会话”。如何从FirebaseAuth mAuth对象获取访问令牌???…非常感谢。指向文档的链接如下所示

public类MainActivity扩展了AppCompatActivity{
私有静态最终字符串TAG=“NearGoal”;
专用工具栏;
私人摊位摊位;
私人视页机视页机;
private List causesList=new ArrayList();
private List fundItemList=新建ArrayList();
私人回收车;
私人废物回收公司的目标;
私人原因;
私人原因、适配器、目标附近的适配器;
私人ProgressBar pb;
私人ProgressBar progressBarGral;
私有上下文;
私人消防队;
私有FirebaseAuth.AuthStateListener mAuthListener;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_全屏,WindowManager.LayoutParams.FLAG_全屏);
mAuth=FirebaseAuth.getInstance();
if(mAuth.getCurrentUser()!=null){
//已登录
FirebaseUser FirebaseUser=mAuth.getCurrentUser();
Log.d(“TWITTER\u USER\u INFO”,“”+mAuth.getCurrentUser().getToken(true));
}否则{
startActivityForResult(
AuthUI.getInstance()
.CreateSignInEntBuilder()
.setProviders(Arrays.asList(
新建AuthUI.IdpConfig.Builder(AuthUI.TWITTER\u PROVIDER.build())
.build(),
RC_登录);
}
//TwitterAuthProvider
Fresco.initialize(getApplication());
setContentView(R.layout.activity_main);
rv=(RecyclerView)findViewById(R.id.rv);
rvgoal=(RecyclerView)findViewById(R.id.rvgoal);
RecyclerView.LayoutManager mLayoutManager=新的LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(新的DefaultItemAnimator());
RecyclerView.LayoutManager gLayoutManager=新的LinearLayoutManager(此,LinearLayoutManager.HORIZONTAL,false);
rvgoal.setLayoutManager(gLayoutManager);
rvgoal.setDrawingCacheEnabled(true);
rvgoal.setDrawingCacheQuality(视图.绘图缓存质量高);
setItemAnimator(新的DefaultItemAnimator());
toolbar=(android.support.v7.widget.toolbar)findviewbyd(R.id.toolbar);
设置支持操作栏(工具栏);
工具栏。设置标题(“您的标题”);
//setTitleTextColor(getResources().getColor(android.R.color.transparent));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//tabLayout=(tabLayout)findViewById(R.id.tabs);
//tabLayout.setupWithViewPager(viewPager);
//折叠ToolbarLayout.setTitle(“”);
pb=(ProgressBar)findViewById(R.id.ProgressBar);
progressBarGral=(ProgressBar)findViewById(R.id.progress\U bar);
//字符串url=”http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/";
新建下载任务().execute();;
mAuthListener=new FirebaseAuth.AuthStateListener(){
@凌驾
AuthStateChanged上的公共void(@NonNull FirebaseAuth FirebaseAuth){
FirebaseUser=firebaseAuth.getCurrentUser();
如果(用户!=null){
//用户已登录
Log.d(标记为“+user.getUid()”);
}否则{
//用户已注销
Log.d(标记“onAuthStateChanged:signed_out”);
}
}
};
}
公共类DownloadTask扩展了AsyncTask{
URL=null;
@凌驾
受保护的void onPreExecute(){
progressBarGral.setVisibility(视图可见);
}
@凌驾
受保护的整数doInBackground(字符串…参数){
整数结果=0;
HttpURLConnection-urlConnection;
试一试{
url=新url(getResources().getString(R.string.backend_base_url)+“/api/campaiments/get/all/”;
urlConnection=(HttpURLConnection)url.openConnection();
int statusCode=urlConnection.getResponseCode();
//200表示HTTP OK
如果(状态代码==200){
BufferedReader r=新的BufferedReader(新的InputStreamReader(urlConnection.getInputStream());
StringBuilder响应=新建StringBuilder();
弦线;
而((line=r.readLine())!=null){
响应。追加(行);
}
parseResult(response.toString());
结果=1;//成功
}否则{
结果=0;//“无法获取数据!”;
}
}捕获(例外e){
Log.d(标记,例如getLocalizedMessage());
}
返回结果;//“无法获取数据!”;
}
@凌驾
受保护的void onPostExecute(整数结果){
progressBarGral.setVisibility(View.GONE);
如果(结果==1){
gAdapter=目标附近的新原因(MainActivity.this,原因列表);
//gAdapter=目标附近的新原因(getApplicationContext(),原因列表);
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);
        }
    }




 }
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);
    }
});
@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();
        }
    }