Advertisement
Guest User

Untitled

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