Я использую firebase-UI для входа в систему с помощью твиттера, и теперь, как говорят документы, я должен получить токен доступа, используя метод private void handleTwitterSession(TwitterSession session)
. Вход работает нормально, но я не знаю, что отправить этой функции так называемому «сеансу». Как получить токен доступа от объекта mAb FirebaseAuth? ... Большое спасибо. Ссылки на документы являются это https://firebase.google.com/docs/auth/android/twitter-loginTwitter API с использованием Firebase: как получить твиттер 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);
}
}
}
У меня нет mLoginButton ... Я использую активность firebase-UI для входа в систему, и это возвращается к коду, указанному выше .... .startActivityForResult ( AuthUI.getInstance() .createSignInIntentBuilder() .setProviders (Arrays.asList () 0 новый AuthUI.IdpConfig.Builder (AuthUI.TWITTER_PROVIDER) .build())) .build(), RC_SIGN_IN); это та часть, которая идет на активность входа в случае, если пользователь не вошел в систему, когда они входят в основное действие – Juan