Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package intermex.producto.lennken.intermex.Activities;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.annotation.TargetApi;
- import android.app.ActivityManager;
- import android.app.ProgressDialog;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.content.pm.PackageInfo;
- import android.content.pm.PackageManager;
- import android.graphics.Point;
- import android.location.Location;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Environment;
- import android.os.IBinder;
- import android.os.StatFs;
- import android.support.design.widget.FloatingActionButton;
- import android.support.v7.app.AppCompatActivity;
- import android.telephony.TelephonyManager;
- import android.util.Log;
- import android.view.Display;
- import android.view.inputmethod.InputMethodManager;
- import android.widget.Button;
- import android.widget.TextView;
- import com.crashlytics.android.Crashlytics;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.location.LocationServices;
- import com.google.gson.Gson;
- import com.gun0912.tedpermission.PermissionListener;
- import com.gun0912.tedpermission.TedPermission;
- import com.rengwuxian.materialedittext.MaterialEditText;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.UUID;
- import butterknife.Bind;
- import butterknife.ButterKnife;
- import butterknife.OnClick;
- import dao.Puntovisita;
- import dao.Ruta;
- import dao.Usuarios;
- import intermex.producto.lennken.intermex.Dal.Dao;
- import intermex.producto.lennken.intermex.Dal.GreenDao;
- import intermex.producto.lennken.intermex.Dal.Ws;
- import intermex.producto.lennken.intermex.Interface.OnStageChanged;
- import intermex.producto.lennken.intermex.PromApp;
- import intermex.producto.lennken.intermex.R;
- import intermex.producto.lennken.intermex.models.SystemInfo;
- import intermex.producto.lennken.intermex.models.UserModel;
- import intermex.producto.lennken.intermex.petitions.responses.LoginResponse;
- import intermex.producto.lennken.intermex.petitions.responses.PuntoVisitaResponse;
- import intermex.producto.lennken.intermex.petitions.responses.RutaResponse;
- import intermex.producto.lennken.intermex.receivers.InitTrackingReceiver;
- import intermex.producto.lennken.intermex.receivers.StopTrackingReceiver;
- import intermex.producto.lennken.intermex.receivers.SyncUbicationReceiver;
- import intermex.producto.lennken.intermex.services.SignalService;
- import intermex.producto.lennken.intermex.services.TrackerService;
- import intermex.producto.lennken.intermex.utils.Constants;
- import intermex.producto.lennken.intermex.utils.PlayServices;
- import intermex.producto.lennken.intermex.utils.TrackingCatalogs;
- import intermex.producto.lennken.intermex.utils.ValidateServices;
- import lib.lennken.utils.Alerts;
- import lib.lennken.utils.Connection;
- import lib.lennken.utils.Validations;
- import retrofit.Callback;
- import retrofit.RetrofitError;
- import retrofit.client.Response;
- public class LoginActivity extends AppCompatActivity
- implements
- PlayServices.OnRegisteredDevice, GoogleApiClient.ConnectionCallbacks,
- GoogleApiClient.OnConnectionFailedListener {
- public final static String TAG = LoginActivity.class.getName();
- //region INJECTS
- @Bind(R.id.act_login_username)
- MaterialEditText edtUsername;
- @Bind(R.id.act_login_password)
- MaterialEditText edtPassword;
- @Bind(R.id.act_login_version)
- TextView txtVersion;
- @Bind(R.id.act_login_restore)
- FloatingActionButton fbRestore;
- //endregion INJECTS
- //region FIELDS
- TrackerService mTrackerService = new TrackerService();
- InitTrackingReceiver initTracking = new InitTrackingReceiver();
- SyncUbicationReceiver syncUbication = new SyncUbicationReceiver();
- StopTrackingReceiver stopTracking = new StopTrackingReceiver();
- public static Location mLastLocation;
- private boolean mIsBound;
- Intent serviceIntent;
- ProgressDialog mProgressDialog;
- String pushId;
- private static final long KILOBYTE = 1024;
- UserModel mUser;
- Usuarios user;
- private int buttonCont = 0;
- private GoogleApiClient mGoogleApiClient;
- Location mLocation;
- final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
- ArrayList<String> dangerousPermissions;
- SimpleDateFormat simpleDateFormat;
- String time;
- Calendar calander;
- //endregion FIELDS
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- ButterKnife.bind(this);
- initPermissions();
- ValidateServices.checkGooglePlayServices(this);
- ValidateServices.checkLocationEnabled(this);
- // mTrackerService = new TrackerService();
- calander = Calendar.getInstance();
- simpleDateFormat = new SimpleDateFormat("HH:mm");
- time = simpleDateFormat.format(calander.getTime());
- Log.d(TAG, "FECHA ACTUAL " + time);
- buildGoogleApiClient();
- if (getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getBoolean
- (Constants.INTERMEX_LOGIN_PREFS, false)) {
- startActivity(new Intent(LoginActivity.this, MainActivity.class));
- finish();
- }
- serviceIntent = new Intent(this, TrackerService.class);
- try {
- initTracking.setAlarm(this);
- syncUbication.setSync(this);
- stopTracking.setAlarm(this);
- } catch (Exception e) {
- Crashlytics.logException(e);
- Log.d(TAG, "ERRor en syncUbication " + e.getMessage());
- }
- mLastLocation = mTrackerService.getmLastLocationFromTracker();
- PlayServices playServices = new PlayServices(this,
- Constants.PREFS_NAME, Constants.SENDER_ID, this);
- playServices.register();
- PackageInfo mPackageInfo;
- try {
- mPackageInfo = getPackageManager()
- .getPackageInfo(getPackageName(), 0);
- String mVersion = mPackageInfo.versionName;
- txtVersion.setText("Versión : " + mVersion);
- } catch (PackageManager.NameNotFoundException e) {
- Crashlytics.logException(e);
- e.printStackTrace();
- }
- //Realm's Structure validate to delete
- if (!getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).getBoolean
- (Constants.INTERMEX_DELETE_REALM, false)) {
- Dao.deleteRealm(LoginActivity.this);
- getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).edit().putBoolean
- (Constants.INTERMEX_DELETE_REALM, true).commit();
- }
- }
- //regionClick
- @OnClick(R.id.act_login_signin)
- void onLoginClick(Button btn) {
- if (ValidateServices.checkLocationEnabled(LoginActivity.this)) {
- ValidateServices.showGPSMessage(LoginActivity.this);
- } else {
- try {
- InputMethodManager inputManager = (InputMethodManager)
- getSystemService(Context.INPUT_METHOD_SERVICE);
- inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
- InputMethodManager.HIDE_NOT_ALWAYS);
- } catch (Exception e) {
- e.printStackTrace();
- Crashlytics.logException(e);
- Log.d(TAG, "Error in hint keyboard " + e.getMessage());
- }
- ValidateServices.checkLocationEnabled(LoginActivity.this);
- buildGoogleApiClient();
- initFields();
- if (mGoogleApiClient.isConnected()) {
- mGoogleApiClient.disconnect();
- mGoogleApiClient.connect();
- } else {
- mGoogleApiClient.connect();
- }
- final String username = edtUsername.getText().toString().trim().toUpperCase();
- final String password = edtPassword.getText().toString().trim();
- if (Validations.validNotNull(username).isEmpty()) {
- Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_user_login));
- } else {
- if (Validations.validNotNull(password).isEmpty()) {
- Alerts.showAlertMessage(LoginActivity.this, getResources().getString(R.string.msg_error_pass_login));
- } else {
- mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading));
- mProgressDialog.setCancelable(false);
- if (Connection.isConnected(this)) {
- PlayServices playServices = new PlayServices(this,
- Constants.PREFS_NAME, Constants.SENDER_ID, this);
- playServices.register();
- PromApp.getLnkService().login("mobile", "password",
- username,
- password,
- Ws.getImei(this, LoginActivity.this),
- pushId,
- getPhoneNumber(),
- //Todo: Buscar un metodo mas adecuado para obtener las coordenadas en tiempo real
- String.valueOf(mLocation == null ? 0.0 : mLocation.getLatitude()),
- String.valueOf(mLocation == null ? 0.0 : mLocation.getLongitude()),
- getSystemInfoJson(getSystemInfo()),
- new Callback<LoginResponse>() {
- @Override
- public void success(
- LoginResponse loginResponse, Response response) {
- if (response.getStatus() == 200) {
- initCrashLitycs(username,
- Ws.getImei(LoginActivity.this,
- LoginActivity.this),
- intermex.producto.lennken.intermex.
- BuildConfig.VERSION_NAME);
- GreenDao.deleteUserGreen();
- user = new Usuarios();
- user.setExpires(loginResponse.getExpires());
- user.setExpiresin(loginResponse.getExpiresIn());
- user.setImei(Ws.getImei(LoginActivity.this, LoginActivity.this));
- user.setIssued(loginResponse.getIssued());
- user.setPhone(getPhoneNumber());
- user.setProviderkey(loginResponse.getProviderKey());
- user.setPushid(pushId);
- user.setToken(loginResponse.getAccessToken());
- user.setUsername(username);
- user.setPassword(password);
- user.setIssenior(loginResponse.getRol().
- contains("M_SUPERVISOR"));
- user.setSurveystype(loginResponse.getSurveysType()
- != null && !loginResponse.getSurveysType().
- isEmpty() ? loginResponse.getSurveysType()
- : "NULL");
- GreenDao.saveUser(user);
- getSharedPreferences(Constants.INTERMEX_PREFS,
- Context.MODE_PRIVATE).edit().putString
- (Constants.INTERMEX_USERNAME_PREFS,
- username).commit();
- getSharedPreferences(Constants.INTERMEX_PREFS,
- Context.MODE_PRIVATE).edit().putString
- (Constants.INTERMEX_TOKEN_PREFS,
- loginResponse.getAccessToken()).commit();
- getSharedPreferences(Constants.INTERMEX_PREFS,
- Context.MODE_PRIVATE).edit().putString
- (Constants.INTERMEX_PROVIDERKEY_PREFS,
- loginResponse.getProviderKey()).commit();
- getSharedPreferences(Constants.INTERMEX_PREFS,
- Context.MODE_PRIVATE).edit().putBoolean
- (Constants.INTERMEX_LOGIN_PREFS, true).commit();
- getRute(loginResponse.getAccessToken());
- }
- }
- @Override
- public void failure(RetrofitError error) {
- initCrashLitycs(username, Ws.getImei(LoginActivity.this,
- LoginActivity.this), intermex.producto.lennken.
- intermex.BuildConfig.VERSION_NAME);
- if (error != null && error.getResponse() != null) {
- if (!error.getMessage().contains("host")) {
- try {
- Gson gson = new Gson();
- String loginString = gson.toJson(error.
- getBody());
- LoginResponse loginResponse = gson.fromJson
- (loginString, LoginResponse.class);
- if (loginResponse != null) {
- Alerts.showAlertMessage(LoginActivity.this,
- Validations.validNotNull(loginResponse.
- getErrorDescription()).isEmpty() ?
- error.getMessage() :
- loginResponse.getErrorDescription());
- } else {
- Alerts.showAlertMessage(LoginActivity.this,
- error.getMessage());
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- Alerts.showAlertMessage(LoginActivity.this,
- error.getMessage());
- Crashlytics.logException(ex);
- }
- } else if (error.getMessage().contains("SSL") ||
- error.getMessage().contains("timeout")) {
- Crashlytics.logException(error);
- Alerts.showAlertMessage(LoginActivity.this,
- getResources().getString(R.string.msg_error_server_again));
- } else {
- Alerts.showAlertMessage(LoginActivity.this,
- getResources().getString(R.string.msg_error_server_again));
- Crashlytics.logException(error);
- }
- }
- mProgressDialog.dismiss();
- }
- }
- );
- } else {
- mProgressDialog.dismiss();
- user = GreenDao.getUser(LoginActivity.this);
- if (user == null) {
- Alerts.showAlertMessage(this, getResources().getString(R.string.msg_error_server));
- } else {
- getSharedPreferences(Constants.INTERMEX_PREFS, Context.MODE_PRIVATE).
- edit().putBoolean
- (Constants.INTERMEX_LOGIN_PREFS, true).commit();
- startActivity(new Intent(LoginActivity.this, MainActivity.class));
- 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);
- finish();
- }
- }
- }
- }
- }
- }
- @OnClick(R.id.act_login_restore)
- void onRestoreClick() {
- if (!getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).
- contains(Constants.INTERMEX_DELETE_ALL)) {
- clearApplicationData(LoginActivity.this);
- getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).edit().
- putInt(Constants.INTERMEX_DELETE_ALL, 2).commit();
- Log.d(TAG, "consta " + getSharedPreferences(Constants.PREFS_NAME,
- Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0));
- } else {
- int cont = getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).
- getInt(Constants.INTERMEX_DELETE_ALL, 0);
- if (cont > 5) {
- Alerts.showToastMessage(LoginActivity.this, "Ya no se puede restaurar la aplicación");
- } else {
- clearApplicationData(LoginActivity.this);
- cont++;
- getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).edit().putInt
- (Constants.INTERMEX_DELETE_ALL, cont).commit();
- Log.d(TAG, "consta " + getSharedPreferences(Constants.PREFS_NAME,
- Context.MODE_PRIVATE).getInt(Constants.INTERMEX_DELETE_ALL, 0));
- }
- }
- }
- public static void clearApplicationData(Context context) {
- Log.d(TAG, "ENTRO EN EL CLEARAPPLICATIODATA");
- File cache = context.getCacheDir();
- File appDir = new File(cache.getParent());
- if (appDir.exists()) {
- String[] children = appDir.list();
- for (String s : children) {
- File f = new File(appDir, s);
- if (!f.getAbsolutePath().contains("shared_prefs")) {
- if (deleteDir(f)) {
- Log.i(TAG,
- String.format("**************** DELETED -> (%s) *******************",
- f.getAbsolutePath()));
- }
- } else {
- Log.i(TAG,
- String.format("**************** DELETED -> (%s) ******************* " +
- "NOT DELETE", f.getAbsolutePath()));
- }
- }
- }
- }
- private static boolean deleteDir(File dir) {
- Log.d(TAG, "ENTRO EN EL DELETEDIR");
- if (dir != null && dir.isDirectory()) {
- String[] children = dir.list();
- for (int i = 0; i < children.length; i++) {
- boolean success = deleteDir(new File(dir, children[i]));
- if (!success) {
- return false;
- }
- }
- }
- return dir.delete();
- }
- @OnClick(R.id.act_login_version)
- void onChangeEndPoint() {
- buttonCont++;
- if (buttonCont == 15) {
- buttonCont = 0;
- intermex.producto.lennken.intermex.utils.Utils.changeStage(this, new OnStageChanged() {
- @SuppressLint("SetTextI18n")
- @Override
- public void onChange() {
- }
- });
- }
- }
- //endregion
- //regionMethods
- public void getRute(String token) {
- PromApp.getLnkService().getRoutes("bearer " + token,
- new Callback<ArrayList<PuntoVisitaResponse>>() {
- @Override
- public void success(ArrayList<PuntoVisitaResponse> puntoVisitaResponses,
- Response response) {
- if (puntoVisitaResponses.size() > 0) {
- GreenDao.deletePdv();
- for (PuntoVisitaResponse pvr : puntoVisitaResponses) {
- Puntovisita pv = new Puntovisita();
- pv.setCvepuntovisita(pvr.getKey());
- pv.setNombre(pvr.getName());
- pv.setDireccion(pvr.getAddress());
- pv.setLatitud(pvr.getLatitude());
- pv.setLongitud(pvr.getLongitude());
- pv.setC1(pvr.getC1());
- pv.setC2(pvr.getC2());
- pv.setC3(pvr.getC3());
- pv.setC4(pvr.getC4());
- pv.setC5(pvr.getC5());
- pv.setC6(pvr.getC6());
- pv.setC7(pvr.getC7());
- pv.setC8(pvr.getC8());
- pv.setC9(pvr.getC9());
- pv.setC10(pvr.getC10());
- pv.setC11(pvr.getC11());
- pv.setC12(pvr.getC12());
- pv.setC13(pvr.getC13());
- pv.setC14(pvr.getC14());
- pv.setC15(pvr.getC15());
- pv.setC16(pvr.getC16());
- pv.setC17(pvr.getC17());
- pv.setC18(pvr.getC18());
- pv.setC19(pvr.getC19());
- pv.setC20(pvr.getC20());
- long id = GreenDao.insertPdv(pv);
- if (pvr.getRutas().size() > 0 && id > 0) {
- ArrayList<Ruta> arrRuta = new ArrayList<Ruta>();
- for (RutaResponse rutares : pvr.getRutas()) {
- Ruta ruta = new Ruta();
- ruta.setCvepuntovisita(rutares.getCheckPointKey());
- ruta.set_idpuntovisita(id);
- ruta.setCvepersona(rutares.getPearsonKey());
- ruta.setCveruta(rutares.getRutaid());
- ruta.setFecha(rutares.getDate());
- ruta.setOrden(rutares.getOrder());
- ruta.setUuid(UUID.randomUUID().toString());
- arrRuta.add(ruta);
- }
- GreenDao.insertRute(arrRuta);
- }
- GreenDao.updateRutaStatusGral();
- }
- }
- //TODO:Empezar la descarga de encuestas schemas
- if (mProgressDialog.isShowing()) {
- mProgressDialog.dismiss();
- } else {
- try {
- mProgressDialog.dismiss();
- } catch (Exception e) {
- Crashlytics.logException(e);
- e.printStackTrace();
- }
- }
- startActivity(new Intent(LoginActivity.this, MainActivity.class));
- finish();
- }
- @Override
- public void failure(RetrofitError error) {
- if (error != null && error.getResponse() != null &&
- error.getResponse().getStatus() == 204) {
- Alerts.showToastMessage(LoginActivity.this, "No existe ruta asignada");
- } else {
- if (error != null) {
- Alerts.showToastMessage(LoginActivity.this,
- Validations.validNotNull(error.getMessage()));
- }
- }
- mProgressDialog.dismiss();
- startActivity(new Intent(LoginActivity.this, MainActivity.class));
- finish();
- }
- });
- }
- public String getPhoneNumber() {
- TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
- return Validations.validNotNull(tMgr.getLine1Number());
- }
- public String getSystemInfoJson(SystemInfo systemInfo) {
- Gson gson = new Gson();
- String json = gson.toJson(systemInfo);
- return json;
- }
- @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
- public SystemInfo getSystemInfo() {
- String deviceInfo = System.getProperty("os.version") + " " + android.os.Build.DEVICE + " " +
- android.os.Build.MODEL + " " + android.os.Build.PRODUCT;
- Display display = getWindowManager().getDefaultDisplay();
- Point size = new Point();
- display.getSize(size);
- ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
- actManager.getMemoryInfo(memInfo);
- long totalMemory = memInfo.totalMem;
- String serviceName = Context.TELEPHONY_SERVICE;
- TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
- SystemInfo systemInfo = new SystemInfo(android.os.Build.MODEL +
- Build.DEVICE, android.os.Build.BRAND, Build.DISPLAY,
- String.valueOf(size.x + "" + size.y),
- String.valueOf(totalMemory), getTotalStorage(), getFreeStorage(),
- Build.VERSION.RELEASE,
- intermex.producto.lennken.intermex.BuildConfig.VERSION_NAME,
- String.valueOf(Build.VERSION.SDK_INT),
- System.getProperty("os.arch"), System.getProperty("os.arch"),
- SignalService.getSignal(), Ws.getBattery(this));
- return systemInfo;
- }
- public String getTotalStorage() {
- StatFs internalStatFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
- long internalTotal;
- long internalFree;
- StatFs externalStatFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
- long externalTotal;
- long externalFree;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- internalTotal = (internalStatFs.getBlockCountLong() *
- internalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- internalFree = (internalStatFs.getAvailableBlocksLong() *
- internalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- externalTotal = (externalStatFs.getBlockCountLong() *
- externalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- externalFree = (externalStatFs.getAvailableBlocksLong() *
- externalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- } else {
- internalTotal = ((long) internalStatFs.getBlockCount() *
- (long) internalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- internalFree = ((long) internalStatFs.getAvailableBlocks() *
- (long) internalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- externalTotal = ((long) externalStatFs.getBlockCount() *
- (long) externalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- externalFree = ((long) externalStatFs.getAvailableBlocks() *
- (long) externalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- }
- long total = internalTotal + externalTotal;
- return String.valueOf(total);
- }
- public String getFreeStorage() {
- StatFs internalStatFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
- long internalTotal;
- long internalFree;
- StatFs externalStatFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
- long externalTotal;
- long externalFree;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- internalTotal = (internalStatFs.getBlockCountLong() *
- internalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- internalFree = (internalStatFs.getAvailableBlocksLong() *
- internalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- externalTotal = (externalStatFs.getBlockCountLong() *
- externalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- externalFree = (externalStatFs.getAvailableBlocksLong() *
- externalStatFs.getBlockSizeLong()) / (KILOBYTE * KILOBYTE);
- } else {
- internalTotal = ((long) internalStatFs.getBlockCount() *
- (long) internalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- internalFree = ((long) internalStatFs.getAvailableBlocks() *
- (long) internalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- externalTotal = ((long) externalStatFs.getBlockCount() *
- (long) externalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- externalFree = ((long) externalStatFs.getAvailableBlocks() *
- (long) externalStatFs.getBlockSize()) / (KILOBYTE * KILOBYTE);
- }
- long free = internalFree + externalFree;
- return String.valueOf(free);
- }
- public String getCpuInfo() {
- try {
- Process proc = Runtime.getRuntime().exec("cat /proc/cpuinfo");
- InputStream is = proc.getInputStream();
- return getStringFromInputStream(is);
- } catch (IOException e) {
- Log.e(TAG, "------ getCpuInfo " + e.getMessage());
- Crashlytics.logException(e);
- return "";
- }
- }
- private static String getStringFromInputStream(InputStream is) {
- StringBuilder sb = new StringBuilder();
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- String line = null;
- try {
- while ((line = br.readLine()) != null) {
- sb.append(line);
- sb.append("\n");
- }
- } catch (IOException e) {
- Log.e(TAG, "------ getStringFromInputStream " + e.getMessage());
- Crashlytics.logException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- Log.e(TAG, "------ getStringFromInputStream " + e.getMessage());
- Crashlytics.logException(e);
- }
- }
- }
- return sb.toString();
- }
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API)
- .build();
- }
- private void initCrashLitycs(String user, String imei, String versionApp) {
- Crashlytics.setUserName(user);
- Crashlytics.setUserIdentifier(imei);
- Crashlytics.setString("VersionApp", versionApp);
- }
- //endregion
- //regionoverride
- @Override
- protected void onStop() {
- super.onStop();
- if (mGoogleApiClient.isConnected()) {
- mGoogleApiClient.disconnect();
- }
- }
- @Override
- protected void onStart() {
- super.onStart();
- mGoogleApiClient.connect();
- }
- @Override
- protected void onResume() {
- super.onResume();
- mGoogleApiClient.connect();
- //--TrackerService
- doBindService(true);
- }
- @Override
- protected void onPause() {
- super.onPause();
- if (mGoogleApiClient.isConnected()) {
- mGoogleApiClient.disconnect();
- }
- //--TrackerService
- doUnbindService(false);
- }
- @Override
- protected void onDestroy() {
- if (serviceConnection != null) {
- doUnbindService(false);
- }
- super.onDestroy();
- }
- @Override
- public void onRegistered(String registrationID) {
- pushId = registrationID;
- Log.d("PUSHID", "PUSH " + registrationID);
- }
- @Override
- public void onConnected(Bundle bundle) {
- mLocation = LocationServices.FusedLocationApi.getLastLocation(
- mGoogleApiClient);
- if (mLocation != null) {
- Log.wtf("LOCATION LATITUDE ", String.valueOf(mLocation.getLatitude()));
- Log.wtf("LOCATION LONGITUDE ", String.valueOf(mLocation.getLongitude()));
- } else {
- Log.wtf("LOCATION ERROR", "LOCATION ERROR");
- }
- }
- @Override
- public void onConnectionSuspended(int i) {
- mGoogleApiClient.connect();
- }
- @Override
- public void onConnectionFailed(ConnectionResult connectionResult) {
- Log.wtf("LOCATION ERROR", connectionResult.getErrorMessage());
- }
- private void initFields() {
- try {
- if (!SignalService.isInstanceCreated()) {
- SignalService.requestSignal(this);
- }
- /*if (!LocationService.isInstanceCreated()) {
- LocationService.requestLocation(this);
- }*/
- } catch (NullPointerException ex) {
- ex.printStackTrace();
- Crashlytics.logException(ex);
- }
- }
- private ServiceConnection serviceConnection = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- mTrackerService = ((TrackerService.TrackerBinder) service).getService();
- UpdateStatus();
- mIsBound = true;
- }
- @Override
- public void onServiceDisconnected(ComponentName name) {
- mTrackerService = null;
- }
- };
- private void UpdateStatus() {
- if (mTrackerService.isTracking() && mTrackerService != null) {
- Log.d(TAG, "Tracking enabled. %d locations logged.");
- } else {
- Log.d(TAG, "Tracking not currently enabled.");
- }
- }
- //--BindService logic with flags
- private void doBindService(boolean start) {
- if (start) {
- startService(serviceIntent);
- bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
- mIsBound = true;
- }
- }
- private void doUnbindService(boolean stop) {
- if (mIsBound) {
- unbindService(serviceConnection);
- if (stop)
- stopService(new Intent(this, TrackerService.class));
- mIsBound = false;
- }
- }
- private void initPermissions() {
- PermissionListener permissionlistener = new PermissionListener() {
- @Override
- public void onPermissionGranted() {
- Log.d(TAG, "Permisos concedidos ");
- }
- @Override
- public void onPermissionDenied(ArrayList<String> deniedPermissions) {
- dangerousPermissions = new ArrayList<String>();
- dangerousPermissions = deniedPermissions;
- }
- };
- new TedPermission(LoginActivity.this)
- .setPermissionListener(permissionlistener)
- .setDeniedMessage(
- "Debe de confirmar el uso de los servicios, " +
- "para el buen funcionamiento de la aplicación")
- .setPermissions(Manifest.permission.CALL_PHONE,
- Manifest.permission.ACCESS_FINE_LOCATION,
- Manifest.permission.ACCESS_COARSE_LOCATION,
- Manifest.permission.READ_PHONE_STATE,
- Manifest.permission.WRITE_EXTERNAL_STORAGE,
- Manifest.permission.CAMERA)
- .check();
- }
- //endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement