Advertisement
zalzondabuzz

LoginActivity

Sep 17th, 2019
1,301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 29.44 KB | None | 0 0
  1. package id.jababeka.activity;
  2.  
  3. import android.Manifest;
  4. import android.app.ProgressDialog;
  5. import android.content.BroadcastReceiver;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.IntentSender;
  9. import android.content.pm.PackageInfo;
  10. import android.content.pm.PackageManager;
  11. import android.graphics.Color;
  12. import android.graphics.Paint;
  13. import android.graphics.Typeface;
  14. import android.os.AsyncTask;
  15. import android.os.Build;
  16. import android.os.Bundle;
  17. import android.provider.Settings;
  18. import android.support.v4.app.ActivityCompat;
  19. import android.support.v7.app.AppCompatActivity;
  20. import android.telephony.TelephonyManager;
  21. import android.text.Html;
  22. import android.text.SpannableString;
  23. import android.text.TextPaint;
  24. import android.text.method.LinkMovementMethod;
  25. import android.text.style.ClickableSpan;
  26. import android.view.KeyEvent;
  27. import android.view.View;
  28. import android.view.inputmethod.EditorInfo;
  29. import android.widget.Button;
  30. import android.widget.EditText;
  31. import android.widget.ImageButton;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34. import com.facebook.AccessToken;
  35. import com.facebook.CallbackManager;
  36. import com.facebook.FacebookCallback;
  37. import com.facebook.FacebookException;
  38. import com.facebook.FacebookSdk;
  39. import com.facebook.GraphRequest;
  40. import com.facebook.GraphResponse;
  41. import com.facebook.appevents.AppEventsLogger;
  42. import com.facebook.login.LoginManager;
  43. import com.facebook.login.LoginResult;
  44. import com.google.android.gms.common.ConnectionResult;
  45. import com.google.android.gms.common.GooglePlayServicesUtil;
  46. import com.google.android.gms.common.api.GoogleApiClient;
  47. import com.google.android.gms.maps.model.LatLng;
  48. import com.google.android.gms.plus.Plus;
  49. import com.google.android.gms.plus.model.people.Person;
  50. import org.json.JSONException;
  51. import org.json.JSONObject;
  52. import java.net.SocketTimeoutException;
  53. import java.util.Arrays;
  54. import id.jababeka.networks.ApiResponse;
  55. import id.jababeka.networks.ApiService;
  56. import id.jababeka.helper.BackEndAPI.RestController;
  57. import id.jababeka.helper.GPS.CustomGPSFactory;
  58. import id.jababeka.helper.GPS.GPSTracker;
  59. import id.jababeka.helper.RetroFailureMessageHandler;
  60. import id.jababeka.helper.SessionManager;
  61. import id.jababeka.R;
  62. import id.jababeka.networks.response.model.LoginRetro;
  63. import id.jababeka.utilities.AESCrypt;
  64. import retrofit2.Call;
  65. import retrofit2.Callback;
  66. import retrofit2.Response;
  67.  
  68.  
  69. public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
  70.  
  71.     // LogCat tag
  72.     private static final String TAG = LoginActivity.class.getSimpleName();
  73.     private Button btnLogin;
  74.     private Button btnLinkToRegister;
  75.     private ImageButton fbLoginButton;
  76.     private EditText inputEmail;
  77.     private EditText inputPassword;
  78.     private TextView lupaPassword;
  79.     private TextView signUptext;
  80.     private ProgressDialog pDialog;
  81.     private SessionManager session;
  82.     private TextView loginTitle;
  83.     private String newPassword;
  84.     CallbackManager callbackManager;
  85.     private GoogleApiClient mGoogleApiClient;
  86.     private static final int RC_GOOGLE_SIGN_IN = 9001;
  87.     private static final int RC_FACEBOOK_SIGN_IN = 64206;
  88.     private static final int RC_TWITTER_SIGN_IN = 140;
  89.     private ImageButton signInButton;
  90.     private boolean isProceedSignOut = true;
  91.     /**
  92.      * A flag indicating that a PendingIntent is in progress and prevents us
  93.      * from starting further intents.
  94.      */
  95.     private boolean mIntentInProgress;
  96.     private boolean mSignInClicked;
  97.     private ConnectionResult mConnectionResult;
  98.  
  99.     private BroadcastReceiver mRegistrationBroadcastReceiver;
  100.  
  101.     // tes tes GCM
  102. //    GoogleCloudMessaging gcmObj;
  103.     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
  104.     AsyncTask<Void, Void, String> createRegIdTask;
  105.     public static final String REG_ID = "regId";
  106.     public static final String EMAIL_ID = "emailId";
  107. //    public static final String PREF_USER_FIRST_TIME = "user_forst_time";
  108. //    boolean isUserFirsTime;
  109.  
  110.     String regId = "";
  111.     // tes tes GCM --end
  112.     String fbid = "";
  113.     String fbname = "";
  114.     String fbemail = "";
  115.     String fbgender = "";
  116.     String fbbirthday = "";
  117.     private final int MY_PERMISSIONS_REQUEST_GET_ACCOUNTS = 55;
  118.     private ApiService apiService;
  119.     private GPSTracker gps;
  120.     private String uuid;
  121.  
  122.     @Override
  123.     protected void onCreate(Bundle savedInstanceState) {
  124.         super.onCreate(savedInstanceState);
  125.         // Add code to print out the key hash
  126.         FacebookSdk.sdkInitialize(getApplicationContext());
  127.         callbackManager = CallbackManager.Factory.create();
  128.         AppEventsLogger.activateApp(this);
  129.         setUpApiService();
  130.         setContentView(R.layout.activity_login);
  131.  
  132.  
  133.         // Session manager
  134.         session = new SessionManager(getApplicationContext());
  135.  
  136.         inputEmail = findViewById(R.id.email);
  137.         inputPassword = findViewById(R.id.password);
  138.         lupaPassword = findViewById(R.id.lupa_password);
  139.         btnLogin = findViewById(R.id.btnLogin);
  140.         btnLinkToRegister = findViewById(R.id.btnLinkToRegisterScreen);
  141.         fbLoginButton = findViewById(R.id.btnfacebook_login);
  142.         loginTitle = findViewById(R.id.login_title);
  143.         signUptext = findViewById(R.id.signup_here_text);
  144.         apiService = RestController.getRetrofit(this).create(ApiService.class);
  145.  
  146.         //set font
  147.         Typeface quicksandBold = Typeface.createFromAsset(getAssets(), "quicksand_bold.otf");
  148.         Typeface quicksandBook = Typeface.createFromAsset(getAssets(), "quicksand_book.otf");
  149.         Typeface typeFace = Typeface.createFromAsset(getAssets(), "helvetica.otf");
  150.         inputEmail.setTypeface(typeFace, Typeface.ITALIC);
  151.         inputPassword.setTypeface(typeFace, Typeface.ITALIC);
  152.         btnLogin.setTypeface(typeFace);
  153. //        btnLinkToRegister.setTypeface(typeFace);
  154.         loginTitle.setTypeface(quicksandBold);
  155.         lupaPassword.setTypeface(typeFace);
  156.         signUptext.setTypeface(typeFace);
  157.  
  158.         // set clickable span
  159.         String dontHaveAcc = getString(R.string.text_to_register);
  160.         SpannableString signUpHere = new SpannableString(Html.fromHtml(dontHaveAcc));
  161.         ClickableSpan clickableSpan = new ClickableSpan() {
  162.             @Override
  163.             public void onClick(View widget) {
  164.                 Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
  165.                 startActivity(i);
  166.                 finish();
  167.             }
  168.  
  169.             @Override
  170.             public void updateDrawState(TextPaint ds) {
  171.                 ds.setUnderlineText(false);
  172.             }
  173.         };
  174.  
  175.         signUpHere.setSpan(clickableSpan, 23, 30, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
  176.         signUptext.setText(signUpHere);
  177.         signUptext.setMovementMethod(LinkMovementMethod.getInstance());
  178.         signUptext.setHighlightColor(Color.BLACK);
  179.  
  180.         //set facebook background button
  181.         fbLoginButton.setBackgroundResource(R.drawable.fb_button);
  182.         // Progress dialog
  183.         pDialog = new ProgressDialog(this);
  184.         pDialog.setCancelable(false);
  185.         String dialogMsg = getString(R.string.waiting_response);
  186.         pDialog.setMessage(dialogMsg);
  187.  
  188. //        if (session.isLoggedIn()) {
  189. //            Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
  190. //            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  191. //            startActivity(intent);
  192. //            finish();
  193. //        }
  194.  
  195.         btnLogin.setOnClickListener(new View.OnClickListener() {
  196.             public void onClick(View view) {
  197.                 attemptLogin();
  198.             }
  199.  
  200.         });
  201.  
  202.  
  203.         inputPassword.setOnEditorActionListener(new EditText.OnEditorActionListener() {
  204.             @Override
  205.             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
  206.                 if (actionId == EditorInfo.IME_ACTION_GO) {
  207.                     attemptLogin();
  208.                 }
  209.                 return false;
  210.             }
  211.         });
  212.  
  213.         lupaPassword.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
  214.         lupaPassword.setOnClickListener(new View.OnClickListener() {
  215.             @Override
  216.             public void onClick(View v) {
  217.                 Intent intent = new Intent(getApplicationContext(), ForgotPasswordActivity.class);
  218.                 startActivity(intent);
  219.             }
  220.         });
  221.  
  222.         LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
  223.             @Override
  224.             public void onSuccess(LoginResult loginResult) {
  225.                 AccessToken accessToken = loginResult.getAccessToken();
  226.                 GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
  227.                         new GraphRequest.GraphJSONObjectCallback() {
  228.                             @Override
  229.                             public void onCompleted(JSONObject object, GraphResponse response) {
  230.  
  231.                                 try {
  232.                                     if (object != null) {
  233.                                         fbid = object.getString("id");
  234.                                         fbname = object.getString("first_name");
  235.                                         fbemail = object.getString("email");
  236.                                         if (!fbemail.equals("") && !fbname.equals("")) {
  237.                                             LogInAndRegister(fbemail, fbname);
  238.                                         } else {
  239.                                             String toastText = getString(R.string.user_email_not_exist);
  240.                                             Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT).show();
  241.                                         }
  242.                                     }
  243.                                 } catch (JSONException e) {
  244.  
  245.                                 }
  246.                             }
  247.                         });
  248.                 Bundle parameters = new Bundle();
  249.                 parameters.putString("fields", "id,first_name,email");
  250.                 request.setParameters(parameters);
  251.                 request.executeAsync();
  252.             }
  253.  
  254.             @Override
  255.             public void onCancel() {
  256.                 System.out.println("cancel");
  257.             }
  258.  
  259.             @Override
  260.             public void onError(FacebookException error) {
  261. //                Log.d("LoginActivity", String.valueOf(error));
  262.             }
  263.         });
  264.         fbLoginButton.setOnClickListener(new View.OnClickListener() {
  265.             @Override
  266.             public void onClick(View v) {
  267.                 LoginManager.getInstance().logOut();
  268.                 LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "public_profile"));
  269.             }
  270.         });
  271.  
  272.  
  273. //        fbLoginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
  274. //        fbLoginButton.registerCallback(callbackManager, mCallback);
  275.  
  276.         setUpGoogleSignInComponents();
  277. //        registerGSMService();
  278.  
  279.         TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  280.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
  281.             // TODO: Consider calling
  282.             //    ActivityCompat#requestPermissions
  283.             // here to request the missing permissions, and then overriding
  284.             //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
  285.             //                                          int[] grantResults)
  286.             // to handle the case where the user grants the permission. See the documentation
  287.             // for ActivityCompat#requestPermissions for more details.
  288.             return;
  289.         }
  290.         uuid = tManager.getDeviceId();
  291.     }
  292.  
  293.     private void setUpGoogleSignInComponents() {
  294.  
  295.         // Initializing google plus api client
  296.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  297.                 .addConnectionCallbacks(this)
  298.                 .addOnConnectionFailedListener(this)
  299.                 .addApi(Plus.API)
  300.                 .addScope(Plus.SCOPE_PLUS_LOGIN).build();
  301.  
  302.  
  303.         signInButton = findViewById(R.id.btngoogle_sign_in);
  304.         signInButton.setOnClickListener(this);
  305.  
  306.     }
  307.  
  308.     private void attemptLogin() {
  309.         String email = inputEmail.getText().toString();
  310.         String password = inputPassword.getText().toString();
  311.  
  312.         if (email.trim().length() > 0 && password.trim().length() > 0) {
  313.             checkLogin(email, password, false);
  314.         } else {
  315.             String toastText = getString(R.string.user_insert_username_pass);
  316.             Toast.makeText(getApplicationContext(),
  317.                     toastText, Toast.LENGTH_LONG)
  318.                     .show();
  319.         }
  320.     }
  321.  
  322.     @Override
  323.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  324.         if (requestCode == RC_GOOGLE_SIGN_IN) {
  325.             if (resultCode != RESULT_OK) {
  326.                 mSignInClicked = false;
  327.             }
  328.             mIntentInProgress = false;
  329.             if (!mGoogleApiClient.isConnecting()) {
  330.                 mGoogleApiClient.connect();
  331.             }
  332.         } else if (requestCode == RC_FACEBOOK_SIGN_IN) {
  333.             callbackManager.onActivityResult(requestCode, resultCode, data);
  334.         }
  335.  
  336.     }
  337.  
  338. //
  339.  
  340.     // Check if Google Playservices is installed in Device or not
  341.     private boolean checkPlayServices() {
  342.         int resultCode = GooglePlayServicesUtil
  343.                 .isGooglePlayServicesAvailable(this);
  344.         // When Play services not found in device
  345.         if (resultCode != ConnectionResult.SUCCESS) {
  346.             if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
  347.                 // Show Error dialog to install Play services
  348.                 GooglePlayServicesUtil.getErrorDialog(resultCode, this,
  349.                         PLAY_SERVICES_RESOLUTION_REQUEST).show();
  350.             } else {
  351.                 String toastText = getString(R.string.device_not_support_play_services);
  352.                 Toast.makeText(
  353.                         getApplicationContext(),
  354.                         toastText,
  355.                         Toast.LENGTH_SHORT).show();
  356.                 finish();
  357.             }
  358.             return false;
  359.         }
  360.         return true;
  361.     }
  362.  
  363.  
  364.     private void checkLogin(final String email, final String password, final boolean fblogin) {
  365.  
  366.         showProgressDialog();
  367.         doLogin(email, password);
  368.     }
  369.  
  370.     private void doLogin(final String email, final String password) {
  371.         if (apiService == null) {
  372.             setUpApiService();
  373.         }
  374.         String androidId = Settings.Secure.getString(getContentResolver(),
  375.                 Settings.Secure.ANDROID_ID);
  376.         String app_version = "1";
  377.         String app_origin = getString(R.string.app_name);
  378.         String model_device = Build.MODEL;
  379.         try {
  380.             PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
  381.             app_version = pInfo.versionName;
  382.         } catch (PackageManager.NameNotFoundException e) {
  383.             e.printStackTrace();
  384.         }
  385.  
  386.         try {
  387.             newPassword = AESCrypt.encrypt(password);
  388.         } catch (Exception e) {
  389.             e.printStackTrace();
  390.         }
  391.  
  392.  
  393.         LatLng latLng = CustomGPSFactory.getLatLng(LoginActivity.this,
  394.                 LoginActivity.this);
  395.         Call<ApiResponse<LoginRetro>> loginCall = apiService.Login(email, newPassword,
  396.                 String.valueOf(latLng.latitude), String.valueOf(latLng.longitude),
  397.                 session.getRegId(), app_version, androidId, model_device,app_origin, app_version);
  398.         loginCall.enqueue(new retrofit2.Callback<ApiResponse<LoginRetro>>() {
  399.             @Override
  400.             public void onResponse(Call<ApiResponse<LoginRetro>> call, retrofit2
  401.                     .Response<ApiResponse<LoginRetro>> response) {
  402.                 ApiResponse<LoginRetro> loginApiResponse = response.body();
  403.  
  404.                 if (loginApiResponse != null) {
  405.                     if (loginApiResponse.isCek_status()) {
  406.                         LoginRetro loginRetro = loginApiResponse.getData();
  407.                         String email = loginRetro.getEmail();
  408.                         String token = loginRetro.getToken();
  409.                         String foto_user = loginRetro.getFoto();
  410.                         Integer is_internal = response.body().getData().getIs_internal();
  411. //                        Integer is_internal = 0;
  412.  
  413.                         session.setLogin(email, token, foto_user, is_internal);
  414.                         session.setKeyAkses(loginRetro.getAkses());
  415. //                        session.setLogin(true);
  416.                         checkUser(email,token);
  417. //                        Intent intent = new Intent(LoginActivity.this,
  418. //                                MainTabActivity.class);
  419. //                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  420. //                                Intent.FLAG_ACTIVITY_CLEAR_TASK);
  421. //                        startActivity(intent);
  422. //                        finish();
  423.                     } else {
  424.                         hideProgressDialog();
  425.                         if (loginApiResponse.getMessage() != null){
  426.                             Toast.makeText(getApplicationContext(), loginApiResponse.getMessage(),
  427.                                     Toast.LENGTH_LONG).show();
  428.                         }
  429.                     }
  430.  
  431.                 } else {
  432.                     hideProgressDialog();
  433.                     Toast.makeText(getApplicationContext(), R.string.HTTP_500,
  434.                             Toast.LENGTH_SHORT).show();
  435.                 }
  436.             }
  437.  
  438.             @Override
  439.             public void onFailure(Call<ApiResponse<LoginRetro>> call, Throwable t) {
  440.                 hideProgressDialog();
  441.                 if (t instanceof SocketTimeoutException){
  442.                     Toast.makeText(LoginActivity.this, R.string.server_error,Toast.LENGTH_LONG).show();
  443.                 }else {
  444.                     String errorCause = t.getMessage();
  445.                     RetroFailureMessageHandler.handleMessageError(errorCause,
  446.                             LoginActivity.this);
  447.                 }
  448.             }
  449.         });
  450.     }
  451.  
  452.     private void showProgressDialog() {
  453.         if (!pDialog.isShowing())
  454.             pDialog.show();
  455.     }
  456.  
  457.     private void hideProgressDialog() {
  458.         if (pDialog.isShowing())
  459.             pDialog.dismiss();
  460.     }
  461.  
  462.     @Override
  463.     public void onClick(View v) {
  464.         switch (v.getId()) {
  465.             case R.id.btngoogle_sign_in:
  466.                 isProceedSignOut = false;
  467.                 signIn();
  468.                 break;
  469.         }
  470.     }
  471.  
  472.     private void signIn() {
  473.         if (mGoogleApiClient != null) {
  474.             if (!mGoogleApiClient.isConnecting()) {
  475.                 mSignInClicked = true;
  476.                 mIntentInProgress = true;
  477.                 try {
  478.                     if (mConnectionResult != null) {
  479.                         mConnectionResult.startResolutionForResult(this, RC_GOOGLE_SIGN_IN);
  480.                     } else {
  481.                         mGoogleApiClient.connect();
  482.                     }
  483.  
  484.                 } catch (IntentSender.SendIntentException e) {
  485.                     e.printStackTrace();
  486.                 }
  487.             }
  488.         } else {
  489.             setUpGoogleSignInComponents();
  490.             isProceedSignOut = true;
  491.         }
  492.  
  493.     }
  494.  
  495.     private void resolveSignInError() {
  496.         if (mConnectionResult.hasResolution()) {
  497.             try {
  498.                 mIntentInProgress = true;
  499.                 mConnectionResult.startResolutionForResult(this, RC_GOOGLE_SIGN_IN);
  500.             } catch (IntentSender.SendIntentException e) {
  501.                 e.printStackTrace();
  502.             }
  503.         }
  504.     }
  505.  
  506.  
  507.     @Override
  508.     public void onRestart() {
  509.         super.onRestart();
  510.         mGoogleApiClient.connect();
  511.     }
  512.  
  513.     private void signoutGoogle() {
  514.         if (mGoogleApiClient.isConnected()) {
  515.             Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); //Sign Out
  516.             mGoogleApiClient.disconnect();
  517.             mGoogleApiClient.connect();
  518.         }
  519.     }
  520.  
  521.  
  522.     @Override
  523.     public void onConnected(Bundle bundle) {
  524.         if (isProceedSignOut) {
  525.             signoutGoogle();
  526.         } else {
  527.             mSignInClicked = false;
  528.             RequestPermissonGetAccounts();
  529.         }
  530.  
  531.     }
  532.  
  533.     private void getProfileInformation() {
  534.         try {
  535.             if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
  536.                 Person currentPerson = Plus.PeopleApi
  537.                         .getCurrentPerson(mGoogleApiClient);
  538.                 String personName = currentPerson.getDisplayName();
  539.                 String personPhotoUrl = currentPerson.getImage().getUrl();
  540.                 String personGooglePlusProfile = currentPerson.getUrl();
  541.  
  542.                 if (ActivityCompat.checkSelfPermission(this,
  543.                         Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
  544.                     return;
  545.                 }
  546.                 final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
  547.                 LogInAndRegister(email, personName);
  548.  
  549.             } else {
  550.                 String toastText = getString(R.string.gplus_not_accessible);
  551.                 Toast.makeText(getApplicationContext(),
  552.                         toastText, Toast.LENGTH_LONG).show();
  553.                 signoutGoogle();
  554.             }
  555.         } catch (Exception e) {
  556.             e.printStackTrace();
  557.         }
  558.     }
  559.  
  560.     private void RequestPermissonGetAccounts() {
  561.         ActivityCompat.requestPermissions(this,
  562.                 new String[]{Manifest.permission.GET_ACCOUNTS},
  563.                 MY_PERMISSIONS_REQUEST_GET_ACCOUNTS);
  564.  
  565.     }
  566.  
  567.     public void onRequestPermissionsResult(int requestCode,
  568.                                            String permissions[], int[] grantResults) {
  569.         switch (requestCode) {
  570.             case MY_PERMISSIONS_REQUEST_GET_ACCOUNTS: {
  571.                 if (grantResults.length > 0
  572.                         && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  573.                     getProfileInformation();
  574.                 } else {
  575.                     String toastText = getString(R.string.get_permission_instruction);
  576.                     Toast.makeText(getApplicationContext(),toastText,Toast.LENGTH_SHORT).show();
  577.                 }
  578.                 return;
  579.             }
  580.  
  581.         }
  582.     }
  583.  
  584.     @Override
  585.     public void onConnectionSuspended(int i) {
  586.         mGoogleApiClient.connect();
  587.     }
  588.  
  589.     @Override
  590.     protected void onStart() {
  591.         super.onStart();
  592.         mGoogleApiClient.connect();
  593.     }
  594.  
  595.     @Override
  596.     protected void onStop() {
  597.         super.onStop();
  598.         if (mGoogleApiClient.isConnected()) {
  599.             mGoogleApiClient.disconnect();
  600.         }
  601.     }
  602.  
  603.     @Override
  604.     public void onConnectionFailed(ConnectionResult connectionResult) {
  605.         if (!connectionResult.hasResolution()) {
  606.             GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this,
  607.                     0).show();
  608.             return;
  609.         }
  610.  
  611.         if (!mIntentInProgress) {
  612.             mConnectionResult = connectionResult;
  613.  
  614.             if (mSignInClicked) {
  615.                 resolveSignInError();
  616.             }
  617.         }
  618.     }
  619.  
  620.     private void setUpApiService(){
  621.         if (apiService == null) {
  622.             apiService = RestController.getRetrofit(this).create(ApiService.class);
  623.         }
  624.     }
  625.  
  626.     private void LogInAndRegister(final String email, final String name) {
  627.         if (apiService == null) {
  628.             setUpApiService();
  629.         }
  630.         String androidId = Settings.Secure.getString(getContentResolver(),
  631.                 Settings.Secure.ANDROID_ID);
  632.         String app_version = "1";
  633.         String app_origin = getString(R.string.app_name);
  634.         String model_device = Build.MODEL;
  635.         try {
  636.             PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
  637.             app_version = pInfo.versionName;
  638.         } catch (PackageManager.NameNotFoundException e) {
  639.             e.printStackTrace();
  640.         }
  641.         LatLng latLng = CustomGPSFactory.getLatLng(LoginActivity.this,
  642.                 LoginActivity.this);
  643.         Call<ApiResponse<LoginRetro>> loginAndRegisterCall = apiService.LoginAndRegister(email,
  644.                 name, String.valueOf(latLng.latitude), String.valueOf(latLng.longitude),
  645.                 session.getRegId(), app_version, androidId, model_device, app_origin, app_version);
  646.         showProgressDialog();
  647.         loginAndRegisterCall.enqueue(new retrofit2.Callback<ApiResponse<LoginRetro>>() {
  648.             @Override
  649.             public void onResponse(Call<ApiResponse<LoginRetro>> call, retrofit2
  650.                     .Response<ApiResponse<LoginRetro>> response) {
  651.                 ApiResponse<LoginRetro> loginApiResponse = response.body();
  652.  
  653.                 if (loginApiResponse != null) {
  654.                     if (loginApiResponse.isCek_status()) {
  655.                         LoginRetro loginRetro = loginApiResponse.getData();
  656.                         String email = loginRetro.getEmail();
  657.                         String token = loginRetro.getToken();
  658.                         String foto_user = loginRetro.getFoto();
  659.                         Integer is_internal = response.body().getData().getIs_internal();
  660. //                        Log.d(email, token);
  661.                         session.setLogin(email, token, foto_user, is_internal);
  662.                         session.setKeyAkses(loginRetro.getAkses());
  663. //                        session.setLogin(true);
  664.                         checkUser(email, token);
  665. //                        Intent intent = new Intent(LoginActivity.this,
  666. //                                MainTabActivity.class);
  667. //                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  668. //                                Intent.FLAG_ACTIVITY_CLEAR_TASK);
  669. //                        startActivity(intent);
  670. //                        finish();
  671.                     } else {
  672.                         hideProgressDialog();
  673.                         if (loginApiResponse.getMessage() != null){
  674.                             Toast.makeText(getApplicationContext(), loginApiResponse.getMessage(),
  675.                                     Toast.LENGTH_LONG).show();
  676.                         }
  677.  
  678.                     }
  679.                 } else {
  680.                     hideProgressDialog();
  681.                     Toast.makeText(getApplicationContext(), R.string.HTTP_500,
  682.                             Toast.LENGTH_LONG).show();
  683.                 }
  684.             }
  685.  
  686.             @Override
  687.             public void onFailure(Call<ApiResponse<LoginRetro>> call, Throwable t) {
  688.                 hideProgressDialog();
  689.                 if (t instanceof SocketTimeoutException){
  690.                     Toast.makeText(LoginActivity.this, R.string.server_error,Toast.LENGTH_LONG).show();
  691.                 }else {
  692.                     String errorCause = t.getLocalizedMessage();
  693.                     RetroFailureMessageHandler.handleMessageError(errorCause,
  694.                             LoginActivity.this);
  695.                 }
  696.             }
  697.         });
  698.     }
  699.  
  700.     private void checkUser(final String email, final String token){
  701.         if (apiService == null) {
  702.             setUpApiService();
  703.         }
  704.  
  705.         Call<ApiResponse> dissCallCheckUser = apiService.cekUserOTP(email, token, uuid);
  706.         dissCallCheckUser.enqueue(new Callback<ApiResponse>() {
  707.             @Override
  708.             public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
  709.                 ApiResponse apiResponse = response.body();
  710.                 hideProgressDialog();
  711.                 /*if (apiResponse.isCek_status()){
  712.                     Intent intent = new Intent(LoginActivity.this,
  713.                             MainTabActivity.class);
  714.                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  715.                             Intent.FLAG_ACTIVITY_CLEAR_TASK);
  716.                     startActivity(intent);
  717.                     session.setLogin(true);
  718.                     finish();
  719.                 }else {
  720.                     Intent intent = new Intent(LoginActivity.this, SendOTPActivity.class);
  721.                     startActivity(intent);
  722.                     finish();
  723.                     if (apiResponse.getMessage() != null){
  724.                         Toast.makeText(LoginActivity.this,apiResponse.getMessage(),Toast.LENGTH_LONG).show();
  725.                     }
  726.  
  727.                 }*/
  728.                 Intent intent = new Intent(LoginActivity.this,
  729.                         MainTabActivity.class);
  730.                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  731.                         Intent.FLAG_ACTIVITY_CLEAR_TASK);
  732.                 startActivity(intent);
  733.                 session.setLogin(email, token);
  734.                 finish();
  735.             }
  736.  
  737.             @Override
  738.             public void onFailure(Call<ApiResponse> call, Throwable t) {
  739.                 hideProgressDialog();
  740.                 String errorCause = t.getLocalizedMessage();
  741.                 RetroFailureMessageHandler.handleMessageError(errorCause,
  742.                         LoginActivity.this);
  743.             }
  744.         });
  745.     }
  746.  
  747.  
  748. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement