Advertisement
Guest User

Untitled

a guest
Aug 4th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 47.53 KB | None | 0 0
  1. package intermex.producto.lennken.intermex.Activities;
  2.  
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.annotation.TargetApi;
  6. import android.app.ActivityManager;
  7. import android.app.ProgressDialog;
  8. import android.content.ComponentName;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.ServiceConnection;
  12. import android.content.pm.PackageInfo;
  13. import android.content.pm.PackageManager;
  14. import android.graphics.Point;
  15. import android.location.Location;
  16. import android.os.Build;
  17. import android.os.Bundle;
  18. import android.os.Environment;
  19. import android.os.IBinder;
  20. import android.os.StatFs;
  21. import android.support.annotation.NonNull;
  22. import android.support.design.widget.FloatingActionButton;
  23. import android.support.v7.app.AppCompatActivity;
  24. import android.telephony.TelephonyManager;
  25. import android.util.Log;
  26. import android.view.Display;
  27. import android.view.View;
  28. import android.view.inputmethod.InputMethodManager;
  29. import android.widget.Button;
  30. import android.widget.CheckBox;
  31. import android.widget.EditText;
  32. import android.widget.RelativeLayout;
  33. import android.widget.TextView;
  34.  
  35. import com.crashlytics.android.Crashlytics;
  36. import com.google.android.gms.common.ConnectionResult;
  37. import com.google.android.gms.common.api.GoogleApiClient;
  38. import com.google.android.gms.location.LocationServices;
  39. import com.google.gson.Gson;
  40. import com.gun0912.tedpermission.PermissionListener;
  41. import com.gun0912.tedpermission.TedPermission;
  42.  
  43. import java.io.BufferedReader;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.io.InputStream;
  47. import java.io.InputStreamReader;
  48. import java.text.SimpleDateFormat;
  49. import java.util.ArrayList;
  50. import java.util.Calendar;
  51. import java.util.HashMap;
  52. import java.util.List;
  53. import java.util.Map;
  54. import java.util.UUID;
  55.  
  56. import butterknife.Bind;
  57. import butterknife.ButterKnife;
  58. import butterknife.OnCheckedChanged;
  59. import butterknife.OnClick;
  60. import dao.Puntovisita;
  61. import dao.Ruta;
  62. import dao.Usuarios;
  63. import intermex.producto.lennken.intermex.Dal.Dao;
  64. import intermex.producto.lennken.intermex.Dal.GreenDao;
  65. import intermex.producto.lennken.intermex.Dal.Ws;
  66. import intermex.producto.lennken.intermex.Interface.OnStageChanged;
  67. import intermex.producto.lennken.intermex.PromApp;
  68. import intermex.producto.lennken.intermex.R;
  69. import intermex.producto.lennken.intermex.models.SystemInfo;
  70. import intermex.producto.lennken.intermex.models.UserModel;
  71. import intermex.producto.lennken.intermex.petitions.responses.LoginResponse;
  72. import intermex.producto.lennken.intermex.petitions.responses.PuntoVisitaResponse;
  73. import intermex.producto.lennken.intermex.petitions.responses.RutaResponse;
  74. import intermex.producto.lennken.intermex.receivers.InitTrackingReceiver;
  75. import intermex.producto.lennken.intermex.receivers.StopTrackingReceiver;
  76. import intermex.producto.lennken.intermex.receivers.SyncUbicationReceiver;
  77. import intermex.producto.lennken.intermex.services.SignalService;
  78. import intermex.producto.lennken.intermex.services.TrackerService;
  79. import intermex.producto.lennken.intermex.utils.Constants;
  80. import intermex.producto.lennken.intermex.utils.PlayServices;
  81. import intermex.producto.lennken.intermex.utils.TrackingCatalogs;
  82. import intermex.producto.lennken.intermex.utils.Utils;
  83. import intermex.producto.lennken.intermex.utils.ValidateServices;
  84. import lib.lennken.utils.Alerts;
  85. import lib.lennken.utils.Connection;
  86. import lib.lennken.utils.Validations;
  87. import retrofit.Callback;
  88. import retrofit.RetrofitError;
  89. import retrofit.client.Response;
  90.  
  91. public class LoginActivity extends AppCompatActivity implements PlayServices.OnRegisteredDevice ,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
  92.  
  93. public final static String TAG = LoginActivity.class.getName();
  94. //--regionINJECTS
  95. @Bind(R.id.act_login_username)
  96. EditText edtUsername;
  97. @Bind(R.id.act_login_password)
  98. EditText edtPassword;
  99. @Bind(R.id.act_login_version)
  100. TextView txtVersion;
  101. @Bind(R.id.act_login_restore)
  102. FloatingActionButton fbRestore;
  103. @Bind(R.id.act_login_warning_text)
  104. TextView mWarningText;
  105. @Bind(R.id.act_login_warning_container)
  106. RelativeLayout mWarninContainer;
  107. @Bind(R.id.act_login_remember_me_check)
  108. CheckBox remembermeCheckBox;
  109. //--endregionINJECTS
  110.  
  111. //--regionFIELDS
  112. final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
  113. TrackerService mTrackerService = new TrackerService();
  114. InitTrackingReceiver initTracking = new InitTrackingReceiver();
  115. SyncUbicationReceiver syncUbication = new SyncUbicationReceiver();
  116. StopTrackingReceiver stopTracking = new StopTrackingReceiver();
  117. public static Location mLastLocation;
  118. private boolean mIsBound;
  119. Intent serviceIntent;
  120. ProgressDialog mProgressDialog;
  121. String pushId;
  122. private static final long KILOBYTE = 1024;
  123. UserModel mUser;
  124. Usuarios user;
  125. private int buttonCont = 0, logoCont = 0;
  126. private GoogleApiClient mGoogleApiClient;
  127. Location mLocation;
  128. ArrayList<String> dangerousPermissions ;
  129. SimpleDateFormat simpleDateFormat;
  130. String time;
  131. Calendar calendar;
  132. boolean isCheckedRememberme;
  133. //--endregionFIELDS
  134.  
  135. @Override
  136. protected void onCreate(Bundle savedInstanceState) {
  137. super.onCreate(savedInstanceState);
  138. setContentView(R.layout.activity_login);
  139. ButterKnife.bind(this);
  140.  
  141. if (Build.VERSION.SDK_INT >=23) {
  142. initPermissionsNative();
  143. }
  144.  
  145. ValidateServices.checkGooglePlayServices(this);
  146. ValidateServices.checkLocationEnabled(this);
  147.  
  148. calendar = Calendar.getInstance();
  149. simpleDateFormat = new SimpleDateFormat("HH:mm");
  150.  
  151. time = simpleDateFormat.format(calendar.getTime());
  152.  
  153. Log.d(TAG, "FECHA ACTUAL " + time);
  154.  
  155. buildGoogleApiClient();
  156. if(getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getBoolean
  157. (Constants.INTERMEX_LOGIN_PREFS, false))
  158. {
  159. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  160. finish();
  161. }
  162.  
  163. serviceIntent = new Intent(this,TrackerService.class);
  164. try {
  165. initTracking.setAlarm(this);
  166. syncUbication.setSync(this);
  167. stopTracking.setAlarm(this);
  168. }catch (Exception e){
  169. Crashlytics.logException(e);
  170. Log.d(TAG,"Error in sync Ubication "+e.getMessage());
  171. }
  172.  
  173. mLastLocation = mTrackerService.getmLastLocationFromTracker();
  174.  
  175. PlayServices playServices = new PlayServices(this,
  176. Constants.PREFS_NAME, Constants.SENDER_ID, this);
  177. playServices.register();
  178. PackageInfo mPackageInfo;
  179.  
  180. try {
  181. mPackageInfo =getPackageManager()
  182. .getPackageInfo(getPackageName(), 0);
  183. String mVersion = "Versión " + mPackageInfo.versionName;
  184. txtVersion.setText(mVersion);
  185. } catch (PackageManager.NameNotFoundException e) {
  186. Crashlytics.logException(e);
  187. e.printStackTrace();
  188. }
  189.  
  190. //Realm's Structure validate to delete
  191. if(!getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getBoolean
  192. (Constants.INTERMEX_DELETE_REALM, false)) {
  193. Dao.deleteRealm(LoginActivity.this);
  194. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  195. (Constants.INTERMEX_DELETE_REALM, true).commit();
  196. }
  197. // showButtonRestore();
  198. remembermeCheckBox.setChecked(getSharedPreferences(Constants.INTERMEX_PREFS,
  199. Context.MODE_PRIVATE).getBoolean
  200. (Constants.REMEMBER_FLAG, false));
  201. }
  202.  
  203. //--regionCLICK
  204. @OnClick(R.id.act_login_signin)
  205. void onLoginClick(Button btn){
  206. if (ValidateServices.checkLocationEnabled(LoginActivity.this)){
  207. ValidateServices.showGPSMessage(LoginActivity.this);
  208. }else {
  209. try {
  210. InputMethodManager inputManager = (InputMethodManager)
  211. getSystemService(Context.INPUT_METHOD_SERVICE);
  212. inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
  213. InputMethodManager.HIDE_NOT_ALWAYS);
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. Crashlytics.logException(e);
  217. Log.d(TAG, "Error in hint keyboard " + e.getMessage());
  218. }
  219. ValidateServices.checkLocationEnabled(LoginActivity.this);
  220. buildGoogleApiClient();
  221. initFields();
  222. if (mGoogleApiClient.isConnected()) {
  223. mGoogleApiClient.disconnect();
  224. mGoogleApiClient.connect();
  225. } else {
  226. mGoogleApiClient.connect();
  227. }
  228.  
  229. final String username = edtUsername.getText().toString().trim().toUpperCase();
  230. final String password = edtPassword.getText().toString().trim();
  231. if (Validations.validNotNull(username).isEmpty()) {
  232. Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_user_login));
  233. setWarningText(getResources().getString(R.string.msg_error_user_login));
  234. } else {
  235. if (Validations.validNotNull(password).isEmpty()) {
  236. setWarningText(getResources().getString(R.string.msg_error_pass_login));
  237. Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_pass_login));
  238. } else {
  239. mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading));
  240. mProgressDialog.setCancelable(false);
  241. if (Connection.isConnected(this)) {
  242. PlayServices playServices = new PlayServices(this,
  243. Constants.PREFS_NAME, Constants.SENDER_ID, this);
  244. playServices.register();
  245.  
  246. PromApp.getLnkService().login("mobile", "password",
  247. username,
  248. password,
  249. Ws.getImei(this, LoginActivity.this),
  250. pushId,
  251. getPhoneNumber(),
  252. //Todo: Buscar un metodo mas adecuado para obtener las coordenadas en tiempo real
  253. String.valueOf(mLocation == null ? 0.0 : mLocation.getLatitude()),
  254. String.valueOf(mLocation == null ? 0.0 : mLocation.getLongitude()),
  255. getSystemInfoJson(getSystemInfo()),
  256. new Callback<LoginResponse>() {
  257. @Override
  258. public void success(LoginResponse loginResponse, Response response) {
  259. if (response.getStatus() == 200) {
  260. txtVersion.setVisibility(View.VISIBLE);
  261. mWarninContainer.setVisibility(View.GONE);
  262.  
  263. initCrashLitycs(username, Ws.getImei(LoginActivity.this, LoginActivity.this), intermex.producto.lennken.intermex.BuildConfig.VERSION_NAME);
  264. GreenDao.deleteUserGreen();
  265.  
  266. user = new Usuarios();
  267. user.setExpires(loginResponse.getExpires());
  268. user.setExpiresin(loginResponse.getExpiresIn());
  269. user.setImei(Ws.getImei(LoginActivity.this, LoginActivity.this));
  270. user.setIssued(loginResponse.getIssued());
  271. user.setPhone(getPhoneNumber());
  272. user.setProviderkey(loginResponse.getProviderKey());
  273. user.setPushid(pushId);
  274. user.setToken(loginResponse.getAccessToken());
  275. user.setUsername(username);
  276. user.setPassword(password);
  277. user.setIssenior(loginResponse.getRol().contains("M_SUPERVISOR"));
  278. user.setSurveystype(loginResponse.getSurveysType() != null && !loginResponse.getSurveysType().isEmpty() ? loginResponse.getSurveysType() : "NULL");
  279.  
  280. GreenDao.saveUser(user);
  281.  
  282. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putString
  283. (Constants.INTERMEX_USERNAME_PREFS, username).commit();
  284.  
  285. if(isCheckedRememberme){
  286.  
  287. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  288. .putString(Constants.REMEMBER_USERNAME, username).commit();
  289.  
  290. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  291. .putString(Constants.REMEMBER_PASSWORD, password).commit();
  292.  
  293. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  294. (Constants.REMEMBER_FLAG, true).commit();
  295.  
  296. }else{
  297. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  298. .remove(Constants.REMEMBER_USERNAME).commit();
  299.  
  300. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  301. .remove(Constants.REMEMBER_PASSWORD).commit();
  302. }
  303. //--
  304. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putString
  305. (Constants.INTERMEX_TOKEN_PREFS, loginResponse.getAccessToken()).commit();
  306.  
  307. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putString
  308. (Constants.INTERMEX_PROVIDERKEY_PREFS, loginResponse.getProviderKey()).commit();
  309.  
  310. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  311. (Constants.INTERMEX_LOGIN_PREFS, true).commit();
  312.  
  313. getRute(loginResponse.getAccessToken());
  314.  
  315. }
  316. }
  317.  
  318. @Override
  319. public void failure(RetrofitError error) {
  320.  
  321. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  322. (Constants.REMEMBER_FLAG, false).commit();
  323.  
  324. initCrashLitycs(username, Ws.getImei(LoginActivity.this, LoginActivity.this), intermex.producto.lennken.intermex.BuildConfig.VERSION_NAME);
  325. if (error != null && error.getResponse() != null) {
  326. if (!error.getMessage().contains("host")) {
  327. try {
  328. Gson gson = new Gson();
  329. String loginString = gson.toJson(error.getBody());
  330. LoginResponse loginResponse = gson.fromJson(loginString, LoginResponse.class);
  331. if (loginResponse != null) {
  332.  
  333. if (!Validations.validNotNull(loginResponse.getErrorDescription()).isEmpty()){
  334. if (Utils.containWordInText(loginResponse.getErrorDescription(),"gps") || Utils.containWordInText(error.getMessage(),"gps")){
  335. Alerts.showAlertMessage(LoginActivity.this, R.string.msg_error_gps_no_found);
  336. setWarningText(LoginActivity.this.getResources().getString(R.string.msg_error_gps_no_found));
  337. }else{
  338. Alerts.showAlertMessage(LoginActivity.this, Validations.validNotNull(loginResponse.getErrorDescription()).isEmpty() ? error.getMessage() : loginResponse.getErrorDescription());
  339. setWarningText(Validations.validNotNull(loginResponse.getErrorDescription()).isEmpty() ? error.getMessage() : loginResponse.getErrorDescription());
  340. }
  341. }else{
  342. if (Utils.containWordInText(error.getMessage(),"gps")){
  343. Alerts.showAlertMessage(LoginActivity.this, R.string.msg_error_gps_no_found);
  344. setWarningText(LoginActivity.this.getResources().getString(R.string.msg_error_gps_no_found));
  345. }else{
  346. Alerts.showAlertMessage(LoginActivity.this, error.getMessage());
  347. setWarningText(error.getMessage());
  348. }
  349. }
  350.  
  351. } else {
  352. if (Utils.containWordInText(error.getMessage(),"gps")){
  353. Alerts.showAlertMessage(LoginActivity.this, R.string.msg_error_gps_no_found);
  354. setWarningText(LoginActivity.this.getResources().getString(R.string.msg_error_gps_no_found));
  355. }else{
  356. Alerts.showAlertMessage(LoginActivity.this, error.getMessage());
  357. setWarningText(error.getMessage());
  358. }
  359.  
  360. }
  361. } catch (Exception ex) {
  362. ex.printStackTrace();
  363. if (Utils.containWordInText(error.getMessage(),"gps")){
  364. Alerts.showAlertMessage(LoginActivity.this, R.string.msg_error_gps_no_found);
  365. setWarningText(LoginActivity.this.getResources().getString(R.string.msg_error_gps_no_found));
  366. }else{
  367. Alerts.showAlertMessage(LoginActivity.this, error.getMessage());
  368. setWarningText(error.getMessage());
  369. }
  370. Crashlytics.logException(ex);
  371. }
  372. } else if (error.getMessage().contains("SSL") || error.getMessage().contains("timeout")) {
  373. Crashlytics.logException(error);
  374. Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_server_again));
  375. setWarningText(getResources().getString(R.string.msg_error_server_again));
  376.  
  377. } else {
  378. Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_server_again));
  379. setWarningText(getResources().getString(R.string.msg_error_server_again));
  380. Crashlytics.logException(error);
  381. }
  382.  
  383. }
  384.  
  385. if(mProgressDialog.isShowing()) {
  386. mProgressDialog.dismiss();
  387. }else{
  388. try{
  389. mProgressDialog.dismiss();
  390. }catch (Exception e){
  391. Crashlytics.logException(e);
  392. }
  393. }
  394. }
  395. }
  396. );
  397. } else {
  398. if(mProgressDialog.isShowing()) {
  399. mProgressDialog.dismiss();
  400. }else{
  401. try{
  402. mProgressDialog.dismiss();
  403. }catch (Exception e){
  404. Crashlytics.logException(e);
  405. }
  406. }
  407.  
  408. user = GreenDao.getUser(LoginActivity.this);
  409. if (user == null) {
  410. Alerts.showAlertMessage(this, getResources().getString(R.string.msg_error_server));
  411. setWarningText(getResources().getString(R.string.msg_error_server));
  412. } else {
  413. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  414. (Constants.INTERMEX_LOGIN_PREFS, true).commit();
  415. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  416. Ws.savelocation(LoginActivity.this, TrackerService.getmLastLocationFromTracker(), TrackingCatalogs.LOGIN_OFFLINE, getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getString(Constants.INTERMEX_PROVIDERKEY_PREFS, ""), getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getString(Constants.INTERMEX_USERNAME_PREFS, ""), null, null, null, null, null);
  417. finish();
  418. }
  419. }
  420. }
  421. }
  422. }
  423. }
  424.  
  425. @OnClick(R.id.act_login_restore)
  426. void onRestoreClick(){
  427. if (!getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).contains(Constants.INTERMEX_DELETE_ALL)) {
  428. clearApplicationData(LoginActivity.this);
  429. /*SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
  430. settings.edit().clear().commit();
  431. */
  432. getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).edit().putInt(Constants.INTERMEX_DELETE_ALL, 2).commit();
  433. Log.d(TAG, "consta " + getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0));
  434. }else{
  435. int cont = getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0);
  436. if (cont > 5){
  437. Alerts.showToastMessage(LoginActivity.this, "Ya no se puede restaurar la aplicación");
  438. fbRestore.setVisibility(cont >= 5 ? View.GONE : View.VISIBLE);
  439. }else{
  440. clearApplicationData(LoginActivity.this);
  441. cont++;
  442. getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).edit().putInt(Constants.INTERMEX_DELETE_ALL, cont).commit();
  443. Log.d(TAG, "consta " + getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0));
  444. }
  445. }
  446. }
  447.  
  448. public static void clearApplicationData(Context context) {
  449. Log.d(TAG,"ENTRO EN EL CLEARAPPLICATIODATA");
  450. File cache = context.getCacheDir();
  451. File appDir = new File(cache.getParent());
  452. if (appDir.exists()) {
  453. String[] children = appDir.list();
  454. for (String s : children) {
  455. File f = new File(appDir, s);
  456. if (!f.getAbsolutePath().contains("shared_prefs")) {
  457. if (deleteDir(f)) {
  458. Log.i(TAG, String.format("**************** DELETED -> (%s) *******************", f.getAbsolutePath()));
  459. }
  460. }else{
  461. Log.i(TAG, String.format("**************** DELETED -> (%s) ******************* NOT DELETE", f.getAbsolutePath()));
  462. }
  463. }
  464. }
  465. }
  466.  
  467. private static boolean deleteDir(File dir) {
  468. Log.d(TAG,"ENTRO EN EL DELETEDIR");
  469. if (dir != null && dir.isDirectory()) {
  470. String[] children = dir.list();
  471. for (int i = 0; i < children.length; i++) {
  472. boolean success = deleteDir(new File(dir, children[i]));
  473. if (!success) {
  474. return false;
  475. }
  476. }
  477. }
  478. return dir.delete();
  479. }
  480.  
  481. @OnClick(R.id.act_login_version)
  482. void onChangeEndPoint()
  483. {
  484. buttonCont++;
  485. if (buttonCont == 15) {
  486. buttonCont = 0;
  487. intermex.producto.lennken.intermex.utils.Utils.changeStage(this, new OnStageChanged() {
  488. @SuppressLint("SetTextI18n")
  489. @Override
  490. public void onChange() {
  491.  
  492. }
  493. });
  494. }
  495. }
  496.  
  497. @OnClick(R.id.act_login_img_logo)
  498. void onShowResetButton(){
  499. logoCont++;
  500. if (logoCont == 5){
  501. logoCont = 0;
  502. fbRestore.setVisibility(View.VISIBLE);
  503. }
  504. }
  505.  
  506. //--
  507. private void setCredentialValues(){
  508. String usernameExists =
  509. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).
  510. getString(Constants.REMEMBER_USERNAME, "");
  511.  
  512. String passwordExists =
  513. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).
  514. getString(Constants.REMEMBER_PASSWORD, "");
  515.  
  516. if(!usernameExists.isEmpty() && !passwordExists.isEmpty()){
  517. edtUsername.setText(usernameExists);
  518. edtPassword.setText(passwordExists);
  519. }
  520. }
  521.  
  522. @OnCheckedChanged(R.id.act_login_remember_me_check)
  523. void onRememberMeCheck(boolean isChecked){
  524. isCheckedRememberme = isChecked;
  525.  
  526. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
  527. (Constants.REMEMBER_FLAG, isCheckedRememberme).commit();
  528.  
  529. if(getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getBoolean
  530. (Constants.REMEMBER_FLAG, false)){
  531. setCredentialValues();
  532. }else{
  533. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  534. .remove(Constants.REMEMBER_USERNAME).commit();
  535.  
  536. getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit()
  537. .remove(Constants.REMEMBER_PASSWORD).commit();
  538.  
  539. }
  540. }
  541. //--endregionCLICK
  542. //--regionMETHODS
  543. public void getRute(String token){
  544.  
  545. PromApp.getLnkService().getRoutes(R.string.bearer+token, new Callback<ArrayList<PuntoVisitaResponse>>() {
  546. @Override
  547. public void success(ArrayList<PuntoVisitaResponse> puntoVisitaResponses, Response response) {
  548.  
  549. if(puntoVisitaResponses.size() > 0 ){
  550.  
  551. GreenDao.deletePdv();
  552.  
  553. for (PuntoVisitaResponse pvr : puntoVisitaResponses){
  554. Puntovisita pv = new Puntovisita();
  555. pv.setCvepuntovisita(pvr.getKey());
  556. pv.setNombre(pvr.getName());
  557. pv.setDireccion(pvr.getAddress());
  558. pv.setLatitud(pvr.getLatitude());
  559. pv.setLongitud(pvr.getLongitude());
  560. pv.setC1(pvr.getC1());
  561. pv.setC2(pvr.getC2());
  562. pv.setC3(pvr.getC3());
  563. pv.setC4(pvr.getC4());
  564. pv.setC5(pvr.getC5());
  565. pv.setC6(pvr.getC6());
  566. pv.setC7(pvr.getC7());
  567. pv.setC8(pvr.getC8());
  568. pv.setC9(pvr.getC9());
  569. pv.setC10(pvr.getC10());
  570. pv.setC11(pvr.getC11());
  571. pv.setC12(pvr.getC12());
  572. pv.setC13(pvr.getC13());
  573. pv.setC14(pvr.getC14());
  574. pv.setC15(pvr.getC15());
  575. pv.setC16(pvr.getC16());
  576. pv.setC17(pvr.getC17());
  577. pv.setC18(pvr.getC18());
  578. pv.setC19(pvr.getC19());
  579. pv.setC20(pvr.getC20());
  580. //pv.setCuestionarios(pvr.getSurveysType());
  581.  
  582. long id = GreenDao.insertPdv(pv);
  583.  
  584. if(pvr.getRutas().size() > 0 && id > 0)
  585. {
  586. ArrayList<Ruta> arrRuta = new ArrayList<Ruta>();
  587. for (RutaResponse rutares : pvr.getRutas()){
  588.  
  589. Ruta ruta = new Ruta();
  590. ruta.setCvepuntovisita(rutares.getCheckPointKey());
  591. ruta.set_idpuntovisita(id);
  592. ruta.setCvepersona(rutares.getPearsonKey());
  593. ruta.setCveruta(rutares.getRutaid());
  594. ruta.setFecha(rutares.getDate());
  595. ruta.setOrden(rutares.getOrder());
  596. ruta.setUuid(UUID.randomUUID().toString());
  597. arrRuta.add(ruta);
  598.  
  599. }
  600.  
  601. GreenDao.insertRute(arrRuta);
  602.  
  603. }
  604. GreenDao.updateRutaStatusGral();
  605.  
  606. }
  607.  
  608.  
  609.  
  610. }
  611. //TODO:Empezar la descarga de encuestas schemas
  612. if (mProgressDialog.isShowing()) {
  613. mProgressDialog.dismiss();
  614. }else {
  615. try {
  616. mProgressDialog.dismiss();
  617. }catch (Exception e){
  618. Crashlytics.logException(e);
  619. e.printStackTrace();
  620. }
  621. }
  622. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  623. finish();
  624. }
  625.  
  626. @Override
  627. public void failure(RetrofitError error) {
  628. if (error != null && error.getResponse() != null && error.getResponse().getStatus() == 204){
  629. Alerts.showToastMessage(LoginActivity.this, R.string.no_assigned_route);
  630. }else {
  631. if (error != null) {
  632. Alerts.showToastMessage(LoginActivity.this, Validations.validNotNull(error.getMessage()));
  633. }
  634. }
  635. if (mProgressDialog.isShowing()){
  636. mProgressDialog.dismiss();
  637. }else{
  638. try{
  639. mProgressDialog.dismiss();
  640. }catch (Exception e){
  641. Crashlytics.logException(e);
  642. }
  643. }
  644. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  645. finish();
  646. }
  647. });
  648. }
  649.  
  650. public String getPhoneNumber(){
  651. TelephonyManager tMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  652. return Validations.validNotNull(tMgr.getLine1Number());
  653. }
  654.  
  655. public String getSystemInfoJson(SystemInfo systemInfo){
  656. Gson gson = new Gson();
  657. String json = gson.toJson(systemInfo);
  658. return json;
  659. }
  660.  
  661. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  662. public SystemInfo getSystemInfo(){
  663. String deviceInfo = System.getProperty("os.version")+" "+android.os.Build.DEVICE+" "+android.os.Build.MODEL+" "+android.os.Build.PRODUCT;
  664. Display display = getWindowManager().getDefaultDisplay();
  665. Point size = new Point();
  666. display.getSize(size);
  667. ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  668. ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
  669. actManager.getMemoryInfo(memInfo);
  670. long totalMemory = memInfo.totalMem;
  671.  
  672. String serviceName = Context.TELEPHONY_SERVICE;
  673.  
  674. TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
  675. SystemInfo systemInfo = new SystemInfo(android.os.Build.MODEL+ Build.DEVICE,android.os.Build.BRAND, Build.DISPLAY,String.valueOf(size.x +""+ size.y),
  676. String.valueOf(totalMemory),getTotalStorage(),getFreeStorage(), Build.VERSION.RELEASE,
  677. intermex.producto.lennken.intermex.BuildConfig.VERSION_NAME,
  678. String.valueOf(Build.VERSION.SDK_INT),
  679. System.getProperty("os.arch"),System.getProperty("os.arch"), SignalService.getSignal(), Ws.getBattery(this));
  680. return systemInfo;
  681. }
  682.  
  683. public String getTotalStorage(){
  684. StatFs internalStatFs = new StatFs( Environment.getRootDirectory().getAbsolutePath() );
  685. long internalTotal;
  686. long internalFree;
  687.  
  688. StatFs externalStatFs = new StatFs( Environment.getExternalStorageDirectory().getAbsolutePath() );
  689. long externalTotal;
  690. long externalFree;
  691.  
  692. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  693. internalTotal = ( internalStatFs.getBlockCountLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  694. internalFree = ( internalStatFs.getAvailableBlocksLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  695. externalTotal = ( externalStatFs.getBlockCountLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  696. externalFree = ( externalStatFs.getAvailableBlocksLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  697. }
  698. else {
  699. internalTotal = ( (long) internalStatFs.getBlockCount() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  700. internalFree = ( (long) internalStatFs.getAvailableBlocks() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  701. externalTotal = ( (long) externalStatFs.getBlockCount() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  702. externalFree = ( (long) externalStatFs.getAvailableBlocks() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  703. }
  704.  
  705. long total = internalTotal + externalTotal;
  706. return String.valueOf(total);
  707. }
  708.  
  709. public String getFreeStorage(){
  710. StatFs internalStatFs = new StatFs( Environment.getRootDirectory().getAbsolutePath() );
  711. long internalTotal;
  712. long internalFree;
  713.  
  714. StatFs externalStatFs = new StatFs( Environment.getExternalStorageDirectory().getAbsolutePath() );
  715. long externalTotal;
  716. long externalFree;
  717.  
  718. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  719. internalTotal = ( internalStatFs.getBlockCountLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  720. internalFree = ( internalStatFs.getAvailableBlocksLong() * internalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  721. externalTotal = ( externalStatFs.getBlockCountLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  722. externalFree = ( externalStatFs.getAvailableBlocksLong() * externalStatFs.getBlockSizeLong() ) / ( KILOBYTE * KILOBYTE );
  723. }
  724. else {
  725. internalTotal = ( (long) internalStatFs.getBlockCount() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  726. internalFree = ( (long) internalStatFs.getAvailableBlocks() * (long) internalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  727. externalTotal = ( (long) externalStatFs.getBlockCount() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  728. externalFree = ( (long) externalStatFs.getAvailableBlocks() * (long) externalStatFs.getBlockSize() ) / ( KILOBYTE * KILOBYTE );
  729. }
  730. long free = internalFree + externalFree;
  731. return String.valueOf(free);
  732. }
  733.  
  734. public String getCpuInfo() {
  735. try {
  736. Process proc = Runtime.getRuntime().exec("cat /proc/cpuinfo");
  737. InputStream is = proc.getInputStream();
  738. return getStringFromInputStream(is);
  739. }
  740. catch (IOException e) {
  741. Log.e(TAG, "------ getCpuInfo " + e.getMessage());
  742. Crashlytics.logException(e);
  743. return "";
  744. }
  745. }
  746.  
  747. private static String getStringFromInputStream(InputStream is) {
  748. StringBuilder sb = new StringBuilder();
  749. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  750. String line = null;
  751.  
  752. try {
  753. while((line = br.readLine()) != null) {
  754. sb.append(line);
  755. sb.append("\n");
  756. }
  757. }
  758. catch (IOException e) {
  759. Log.e(TAG, "------ getStringFromInputStream " + e.getMessage());
  760. Crashlytics.logException(e);
  761. }
  762. finally {
  763. if(br != null) {
  764. try {
  765. br.close();
  766. }
  767. catch (IOException e) {
  768. Log.e(TAG, "------ getStringFromInputStream " + e.getMessage());
  769. Crashlytics.logException(e);
  770. }
  771. }
  772. }
  773.  
  774. return sb.toString();
  775. }
  776.  
  777. protected synchronized void buildGoogleApiClient() {
  778. mGoogleApiClient = new GoogleApiClient.Builder(this)
  779. .addConnectionCallbacks(this)
  780. .addOnConnectionFailedListener(this)
  781. .addApi(LocationServices.API)
  782. .build();
  783. }
  784.  
  785. private void initCrashLitycs(String user, String imei, String versionApp){
  786. Crashlytics.setUserName(user);
  787. Crashlytics.setUserIdentifier(imei);
  788. Crashlytics.setString(String.valueOf(R.string.version_app),versionApp);
  789. }
  790. //--endregionMETHODS
  791.  
  792. //--regionOVERRIDE
  793.  
  794. @Override
  795. protected void onStop() {
  796. super.onStop();
  797. if (mGoogleApiClient.isConnected())
  798. {
  799. mGoogleApiClient.disconnect();
  800. }
  801. }
  802.  
  803. @Override
  804. protected void onStart() {
  805. super.onStart();
  806. mGoogleApiClient.connect();
  807. }
  808.  
  809. @Override
  810. protected void onResume() {
  811. super.onResume();
  812. mGoogleApiClient.connect();
  813. //--TrackerService
  814. doBindService(true);
  815. }
  816.  
  817. @Override
  818. protected void onPause() {
  819. super.onPause();
  820. if (mGoogleApiClient.isConnected())
  821. {
  822. mGoogleApiClient.disconnect();
  823. }
  824.  
  825. //--TrackerService
  826. doUnbindService(false);
  827. }
  828.  
  829. @Override
  830. protected void onDestroy() {
  831. if(serviceConnection != null){
  832. doUnbindService(false);
  833. }
  834. super.onDestroy();
  835. }
  836.  
  837. @Override
  838. public void onRegistered(String registrationID) {
  839. pushId = registrationID;
  840. Log.d("PUSHID", "PUSH " + registrationID);
  841.  
  842. }
  843.  
  844.  
  845. @Override
  846. public void onConnected(Bundle bundle) {
  847. mLocation = LocationServices.FusedLocationApi.getLastLocation(
  848. mGoogleApiClient);
  849. if (mLocation != null) {
  850. Log.wtf("LOCATION LATITUDE ",String.valueOf(mLocation.getLatitude()));
  851. Log.wtf("LOCATION LONGITUDE ", String.valueOf(mLocation.getLongitude()));
  852. }else
  853. {
  854. Log.wtf("LOCATION ERROR", "LOCATION ERROR");
  855. }
  856. }
  857.  
  858. @Override
  859. public void onConnectionSuspended(int i) {
  860. mGoogleApiClient.connect();
  861. }
  862.  
  863. @Override
  864. public void onConnectionFailed(ConnectionResult connectionResult) {
  865. Log.wtf("LOCATION ERROR", connectionResult.getErrorMessage());
  866. }
  867.  
  868. private void initFields(){
  869. try {
  870. if (!SignalService.isInstanceCreated()) {
  871. SignalService.requestSignal(this);
  872. }
  873. /*if (!LocationService.isInstanceCreated()) {
  874. LocationService.requestLocation(this);
  875. }*/
  876.  
  877. }catch (NullPointerException ex){
  878. ex.printStackTrace();
  879. Crashlytics.logException(ex);
  880. }
  881. }
  882.  
  883. private ServiceConnection serviceConnection = new ServiceConnection(){
  884. @Override
  885. public void onServiceConnected(ComponentName name, IBinder service) {
  886. mTrackerService = ((TrackerService.TrackerBinder)service).getService();
  887. UpdateStatus();
  888. mIsBound = true;
  889. }
  890. @Override
  891. public void onServiceDisconnected(ComponentName name) {
  892. mTrackerService = null;
  893. }
  894. };
  895.  
  896. private void UpdateStatus(){
  897. if(mTrackerService.isTracking() && mTrackerService != null){
  898. Log.d(TAG, "Tracking enabled. %d locations logged.");
  899. }else{
  900. Log.d(TAG, "Tracking not currently enabled.");
  901. }
  902. }
  903.  
  904. //--BindService logic with flags
  905. private void doBindService(boolean start) {
  906. if (start) {
  907. startService(serviceIntent);
  908. bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
  909. mIsBound = true;
  910. }
  911. }
  912. private void doUnbindService(boolean stop) {
  913. if (mIsBound) {
  914. unbindService(serviceConnection);
  915. if (stop)
  916. stopService(new Intent(this, TrackerService.class));
  917. mIsBound = false;
  918. }
  919. }
  920.  
  921. private void initPermissions(){
  922.  
  923. PermissionListener permissionlistener = new PermissionListener() {
  924. @Override
  925. public void onPermissionGranted() {
  926. Log.d(TAG,"Permisos concedidos ");
  927. }
  928.  
  929. @Override
  930. public void onPermissionDenied(ArrayList<String> deniedPermissions) {
  931. dangerousPermissions = new ArrayList<String>();
  932. dangerousPermissions = deniedPermissions;
  933. }
  934.  
  935. };
  936. new TedPermission(LoginActivity.this)
  937. .setPermissionListener(permissionlistener)
  938. .setDeniedMessage("Debe de confirmar el uso de los servicios, para el buen funcionamiento de la aplicación")
  939. .setPermissions(Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_FINE_LOCATION,
  940. Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE,
  941. Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
  942. .check();
  943. }
  944.  
  945.  
  946. private void showButtonRestore(){
  947. int cont = getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0);
  948. fbRestore.setVisibility(cont >= 5 ? View.GONE : View.VISIBLE);
  949. }
  950.  
  951. void setWarningText(String text){
  952. txtVersion.setVisibility(View.GONE);
  953. mWarninContainer.setVisibility(View.VISIBLE);
  954. mWarningText.setText(text);
  955.  
  956. }
  957.  
  958. @TargetApi(Build.VERSION_CODES.M)
  959. private void initPermissionsNative(){
  960.  
  961. final List<String> permissionsList = new ArrayList<String>();
  962.  
  963. if(!addPermission(permissionsList, Manifest.permission.CALL_PHONE))
  964.  
  965. if(!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
  966.  
  967. if(!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
  968.  
  969. if(!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
  970.  
  971. if(!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
  972.  
  973. if(!addPermission(permissionsList, Manifest.permission.CAMERA))
  974.  
  975. if(!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
  976.  
  977.  
  978. if (permissionsList.size() > 0) {
  979.  
  980. requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
  981. REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
  982. return;
  983. }
  984.  
  985. }
  986.  
  987.  
  988. @TargetApi(Build.VERSION_CODES.M)
  989. private boolean addPermission(List<String> permissionsList, String permission) {
  990. if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
  991. permissionsList.add(permission);
  992. if (!shouldShowRequestPermissionRationale(permission))
  993. return false;
  994. }
  995. return true;
  996. }
  997.  
  998. @Override
  999. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  1000. switch (requestCode) {
  1001. case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
  1002. {
  1003. Map<String, Integer> perms = new HashMap<String, Integer>();
  1004. perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
  1005. perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
  1006. perms.put(Manifest.permission.WRITE_CONTACTS, PackageManager.PERMISSION_GRANTED);
  1007. for (int i = 0; i < permissions.length; i++)
  1008. perms.put(permissions[i], grantResults[i]);
  1009. if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
  1010. && perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
  1011. && perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
  1012. } else {
  1013. Alerts.showToastMessage(LoginActivity.this, R.string.denied_permission_by_user);
  1014. }
  1015. }
  1016. break;
  1017. default:
  1018. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1019. }
  1020. }
  1021. //--endregionOVERRIDE
  1022. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement