Advertisement
Guest User

Untitled

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