2017-03-06 34 views
0

我有一個顯示登錄選項的主要活動,如果用戶點擊用FB按鈕登錄,我會打電話fblogin();,如果登錄成功,那麼我會做意圖打開家庭活動。在Facebook登錄後打開兩次意圖活動

現在,家庭活動似乎打開兩次。 (我可以看到它出現兩次,堆疊)

private void Fblogin() 
{ 
    callbackmanager = CallbackManager.Factory.create(); 

    // Set permissions 
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends")); 

    LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() { 
     @Override 
     public void onSuccess(LoginResult loginResult) { 

      GraphRequest request = GraphRequest.newMeRequest(
        loginResult.getAccessToken(), 
        new GraphRequest.GraphJSONObjectCallback() { 
         @Override 
         public void onCompleted(JSONObject object, GraphResponse response) { 

          Log.d("LoginActivity", response.toString()); 
          Log.d("LoginActivity", object.toString()); 

          String jsonresult = String.valueOf(object); 
          System.out.println("JSON Result" + jsonresult); 
          String str_firstname=null,str_id=null; 


          try { 

           str_firstname=object.getString("name"); 
           str_id = object.getString("id"); 
           String str_email = object.getString("email"); 

           Intent home = new Intent(MainActivity.this , HomeActivity.class); 
           home.putExtra("name", str_firstname); 
           home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE); 
           startActivity(home); 


          } catch (JSONException e) { 
           e.printStackTrace(); 
           Log.d("xxxx","aa"); 
          } 



         } 
        }); 
      Bundle parameters = new Bundle(); 
      parameters.putString("fields", "id,name,email,gender, birthday"); 
      request.setParameters(parameters); 
      request.executeAsync(); 


     } 

     @Override 
     public void onCancel() { 

      Log.v("LoginActivity", "cancel"); 
     } 

     @Override 
     public void onError(FacebookException exception) { 

      Log.v("LoginActivity", exception.getCause().toString()); 

     } 
    }); 
} 

在我的主要活動,我把這個在我的上創建FacebookSdk.sdkInitialize(getApplicationContext());

,II還檢查初始登錄狀態`

if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null) { 

       Intent home = new Intent(MainActivity.this , HomeActivity.class); 
       startActivity(home);} 

,但我認爲,初步覈實有沒有什麼關係呢becauseI試圖刪除它太多,但它仍然happening.`

和在我的家庭活動中,我還沒有寫任何Facebook相關的代碼。

編輯:我把整個代碼(MainActivity)

import ... 

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 


     public static Boolean IsLoggedFB = false; //general state of fb logged 
     public static Boolean IsLoggedManual =false; //status boolean if logged in by email (manual) 
     public static Boolean IsLoggedGM = false; //general state of google gmail logged 


     String ID_HNBS; //IDhnbs created when first Registered 
     String Email; 

     TextView Fpassword; 
     Button Daftar; 
     EditText email, password; 
     Button LoginEmail; 
     LoginButton fb_button; 
     SignInButton gplus_button; 
     MainActivity myContext; 
     static String personName; 
     private boolean mIntentInProgress; 
     FragmentManager fragmentManager; 
     private CallbackManager callbackmanager; 

     //for G+ 
     private GoogleSignInOptions gso; 
     private static final int PROFILE_PIC_SIZE = 30; 
     private GoogleApiClient mGoogleApiClient; 
     private ConnectionResult mConnectionResult; 
     private boolean mSignInClicked; 
     static final int RC_SIGN_IN = 0; 

     /* Is there a ConnectionResult resolution in progress? */ 
     private boolean mIsResolving = false; 

     LinearLayout tv; 
     /* Should we automatically resolve ConnectionResults when possible? */ 
     private boolean mShouldResolve = false; 
     public static final String MyPREFERENCES = "xpp"; 
     SharedPreferences sharedpreferences; 
     @Override 

     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      FacebookSdk.sdkInitialize(getApplicationContext()); 
      setContentView(R.layout.activity_main); 

      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
      SharedPreferences.Editor editor = sharedpreferences.edit(); 


      IsLoggedManual = sharedpreferences.getBoolean("IsLoggedManual", false); // get value of last login status 
      IsLoggedGM = sharedpreferences.getBoolean("IsloggedGM", false); // get value of last login GM 


      Daftar = (Button) findViewById(R.id.buttonDaftarEmail); 
      LoginEmail = (Button) findViewById(R.id.buttonLoginEmail); 
      fb_button = (LoginButton)findViewById(R.id.fblogin_button); 




      //Initializing google signin option 
      gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
        .requestEmail() 
        .build(); 


      gplus_button = (SignInButton) findViewById(R.id.sign_in_button); 
      gplus_button.setSize(SignInButton.SIZE_STANDARD); 
      gplus_button.setScopes(gso.getScopeArray()); 

      //Initializing google api client 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        //.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) 
        .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
        .build(); 



      Daftar.setOnClickListener(this); 
      LoginEmail.setOnClickListener(this); 
      fb_button.setOnClickListener(this); 
      gplus_button.setOnClickListener(this); 

      OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); 
      if (opr.isDone()) 
      { 
       // If the user's cached credentials are valid, the OptionalPendingResult will be "done" 
       // and the GoogleSignInResult will be available instantly. 
       Log.d("TAG", "Got cached sign-in"); 

       GoogleSignInResult result = opr.get(); 

       handleSignInResult(result); 

      } 
      Log.d("TAG", "ACCESS TOKEN STATUS" + AccessToken.getCurrentAccessToken() + " --- profile=" + Profile.getCurrentProfile()); 

      //CHECK IF ALREADY LOGGED BY FB 
      if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null) { 
       //load profile and skip (loginfragment) to Home page 
       Intent home = new Intent(MainActivity.this , HomeActivity.class); 
       startActivity(home); 

      } else if (IsLoggedManual) { //IF already LOGGED IN MANUAL (SHAREDPREF) 
       Intent home = new Intent(MainActivity.this , HomeActivity.class); 
       startActivity(home); 

      } 
     } 


    @Override 
    public void onClick(View v) { 
     if (v.getId() == R.id.buttonDaftarEmail) { 

      Intent intent = new Intent(MainActivity.this, UserRegistration.class); 
      startActivity(intent); 
     } else if (v.getId() == R.id.buttonLoginEmail) { 

      Intent intent_signin = new Intent(MainActivity.this, LoginManual.class); 
      startActivity(intent_signin); 


     } else if (v.getId() == R.id.fblogin_button) { 


      Fblogin(); 

     } else if (v.getId() == R.id.sign_in_button) //google sign in button 
     { 
      Intent intent_Gsignin = new Intent(MainActivity.this, GSignIn.class); 
      startActivity(intent_Gsignin); 
     } 

    } 

    private void onSignInClicked() { 
     // User clicked the sign-in button, so begin the sign-in process and automatically 
     // attempt to resolve any errors that occur. 

     mShouldResolve = true; 
     mGoogleApiClient.connect(); 



    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

    } 


    private void Fblogin() 
    { 
     callbackmanager = CallbackManager.Factory.create(); 

     // Set permissions 
     LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends")); 

     LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() { 
      @Override 
      public void onSuccess(LoginResult loginResult) { 
       // App code 
       GraphRequest request = GraphRequest.newMeRequest(
         loginResult.getAccessToken(), 
         new GraphRequest.GraphJSONObjectCallback() { 
          @Override 
          public void onCompleted(JSONObject object, GraphResponse response) { 
           // Application code 
           Log.d("LoginActivity", response.toString()); 
           Log.d("LoginActivity", object.toString()); 

           String jsonresult = String.valueOf(object); 
           System.out.println("JSON Result" + jsonresult); 
           String str_firstname=null,str_id=null; 


           try { 

            str_firstname=object.getString("name"); 
            str_id = object.getString("id"); 
            String str_email = object.getString("email"); 

            Intent home = new Intent(MainActivity.this , HomeActivity.class); 
            home.putExtra("name", str_firstname); 
            home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE); 
            startActivity(home); 


           } catch (JSONException e) { 
            e.printStackTrace(); 
            Log.d("xxxx","aa"); 
           } 



          } 
         }); 
       Bundle parameters = new Bundle(); 
       parameters.putString("fields", "id,name,email,gender, birthday"); 
       request.setParameters(parameters); 
       request.executeAsync(); 


      } 

      @Override 
      public void onCancel() { 

       Log.v("LoginActivity", "cancel"); 
      } 

      @Override 
      public void onError(FacebookException exception) { 

       Log.v("LoginActivity", exception.getCause().toString()); 

      } 
     }); 
    } 

    //After the signing we are calling this function 
    private void handleSignInResult(GoogleSignInResult result) { 
     //If the login succeed 
     if (result.isSuccess()) { 
      //Getting google account 
      GoogleSignInAccount acct = result.getSignInAccount(); 
      //tv= (LinearLayout) tv.findViewById(R.id.layoutfragmentlogin); 
      //tv.setVisibility(View.GONE); //hide include , so include now show nothing 


      Intent Home=new Intent(this,HomeActivity.class); 
      Home.putExtra("name",acct.getDisplayName()); 
      Home.putExtra("email", acct.getEmail()); 
      Home.putExtra("URL",acct.getPhotoUrl()); 
      startActivity(Home); 

     } else { 
      //If login fails 
      Toast.makeText(this, "Login Failed on silentsign in", Toast.LENGTH_LONG).show(); 
     } 
    } 

    //@Override 
    public void onConnected(Bundle bundle) { 
     mSignInClicked = false; 


     Toast.makeText(myContext, "User is connected!", Toast.LENGTH_LONG).show(); 

    } 

    //@Override 
    public void onConnectionSuspended(int i) { 
     mGoogleApiClient.connect(); 
    } 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if(callbackmanager!=null) { 
      callbackmanager.onActivityResult(requestCode, resultCode, data); 
      Log.d("ani", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data); 
     } 

     if (requestCode == RC_SIGN_IN) { 
      // If the error resolution was not successful we should not resolve further. 
      if (resultCode != this.RESULT_OK) { 
       mShouldResolve = false; 
      } 

      mIsResolving = false; 
      mGoogleApiClient.connect(); 
     } 
    } 

    //@Override 
    public void onConnectionFailed(ConnectionResult connectionResult) 
    { 
     //prefs.edit().putBoolean("Islogin",false).commit(); 
     //DO Nothing.. 


     /* 
     //==========Below is Trying to connect if googleUser not connected already ======= 
     // Could not connect to Google Play Services. The user needs to select an account, 
     // grant permissions or resolve an error in order to sign in. Refer to the javadoc for 
     // ConnectionResult to see possible error codes. 
     Log.d("ani", "onConnectionFailed:" + connectionResult); 

     if (!mIsResolving && mShouldResolve) { 
      if (connectionResult.hasResolution()) { 
       try { 
        connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN); 
        mIsResolving = true; 
       } catch (IntentSender.SendIntentException e) { 
        Log.e("ani", "Could not resolve ConnectionResult.", e); 
        mIsResolving = false; 
        mGoogleApiClient.connect(); 
       } 
      } 
     }*/ 

    } 

    @Override 
    public void onBackPressed() { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage("Are you sure you want to exit?") 
       .setTitle("HnBS Alert") 
       .setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 

         finishAffinity(); 

        } 
       }) 
       .setNegativeButton("No", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.cancel(); 
        } 
       }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 





} 

編輯2:MY HOMEACTIVITY CODE

class ViewPagerAdapter extends FragmentPagerAdapter { 
    private final List<Fragment> mFragmentList = new ArrayList<>(); 
    private final List<String> mFragmentTitleList = new ArrayList<>(); 

    public ViewPagerAdapter(FragmentManager manager) { 
     super(manager); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     return mFragmentList.get(position); 
    } 

    @Override 
    public int getCount() { 
     return mFragmentList.size(); 
    } 

    public void addFragment(Fragment fragment, String title) { 
     mFragmentList.add(fragment); 
     mFragmentTitleList.add(title); 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return mFragmentTitleList.get(position); 
    } 
} 


/** 
* react to the user tapping/selecting an options menu item 
*/ 
@Override 

public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.action_menu_logout: 
      LoginManager.getInstance().logOut(); //LogOut from Facebook 

      //logout from login manual 
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
      SharedPreferences.Editor editor = sharedpreferences.edit(); 
      editor.putBoolean("IsLoggedManual",false).commit(); 

      //if (mGoogleApiClient.isConnected()) { 
       // if (mGoogleApiClient.isConnected()) 
       //  Auth.GoogleSignInApi.signOut(mGoogleApiClient); 

      //} 

      Toast.makeText(this, "LoggedOut!", Toast.LENGTH_SHORT).show(); 
      finish(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 

@Override 
public void onBackPressed() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setMessage("Are you sure you want to exit?") 
      .setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 

        finishAffinity(); 

       } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        dialog.cancel(); 
       } 
      }); 
    AlertDialog alert = builder.create(); 
    alert.show(); 
} 

}

+0

如果可能,請發佈您的整個班級。 – Wizard

+0

這是因爲你是在你登錄後的兩個startCtrivity中的mainactivity被調用的! –

+0

@Wizard,我更新了代碼。 –

回答

0

經過八個小時的試用一些調試,我找不到任何跟蹤導致我的HomeActivity兩次觸發。對於誰停留在任何類似的情況下,如果你想,如果它不是打破了你的代碼,你可以嘗試讓你的活動似乎只有一個實例在清單中添加此對您的活動聲明人:

android:launchMode = "singleTask" 

這一直是我現在的解決方案,因爲我不想浪費任何時間,因爲我需要繼續前進到下一個進度。感謝您的幫助。

0

你兩次調用活動。這是 當考慮如果你登錄Facebook和谷歌然後這兩個代碼得到執行。

中的onCreate您呼叫

​​3210

if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null) { 
       //load profile and skip (loginfragment) to Home page 
       Intent home = new Intent(MainActivity.this , HomeActivity.class); 
       startActivity(home); 

      } else if (IsLoggedManual) { //IF already LOGGED IN MANUAL (SHAREDPREF) 
       Intent home = new Intent(MainActivity.this , HomeActivity.class); 
       startActivity(home); 

      } 

使用這些條件作爲一個如

opr.isDone() || AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null 
+0

這回答了它。 – Wizard

+0

我試圖評論每個部分,但仍然是相同的。 –

+0

試着一起評論一下呢? –

0

在這裏,你錯過了,看看這個代碼 -

OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); 
     if (opr.isDone()) { 
      // If the user's cached credentials are valid, the OptionalPendingResult will be "done" 
      // and the GoogleSignInResult will be available instantly. 
      Log.d("TAG", "Got cached sign-in"); 

      GoogleSignInResult result = opr.get(); 

      handleSignInResult(result); 
     } 

以上緩存登錄將開始HomeActivity還有,如果你的的accessToken不null(你登錄用facebook) - 重新開始家庭活動

 //CHECK IF ALREADY LOGGED BY FB 
     if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null) { 
      //load profile and skip (loginfragment) to Home page 
      Intent home = new Intent(MainActivity.this , HomeActivity.class); 
      startActivity(home); 
     } 

解決方案:
你應該把這些條件使用else if ladder報表...

+0

在谷歌緩存不會開始,因爲我從來沒有登錄谷歌。我重新安裝新的,刪除我的手機中的所有應用程序。也嘗試註釋startActivity(intent)代碼,我的sharedpref也null,我檢查它。 –

+0

我只是添加我的家庭活動類代碼,請看看 –

相關問題