Advertisement
lesjaw

Untitled

May 8th, 2018
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 109.43 KB | None | 0 0
  1. package com.lesjaw.wamonitoring.ui;
  2.  
  3. import android.Manifest;
  4. import android.animation.ArgbEvaluator;
  5. import android.animation.ValueAnimator;
  6. import android.annotation.SuppressLint;
  7. import android.app.Activity;
  8. import android.app.PendingIntent;
  9. import android.app.ProgressDialog;
  10. import android.app.Service;
  11. import android.appwidget.AppWidgetManager;
  12. import android.content.BroadcastReceiver;
  13. import android.content.ComponentName;
  14. import android.content.ContentResolver;
  15. import android.content.Context;
  16. import android.content.DialogInterface;
  17. import android.content.Intent;
  18. import android.content.IntentFilter;
  19. import android.content.SharedPreferences;
  20. import android.content.pm.PackageManager;
  21. import android.content.pm.ResolveInfo;
  22. import android.graphics.Bitmap;
  23. import android.graphics.BitmapFactory;
  24. import android.graphics.Color;
  25. import android.graphics.drawable.ColorDrawable;
  26. import android.location.Address;
  27. import android.location.Geocoder;
  28. import android.location.Location;
  29. import android.location.LocationListener;
  30. import android.location.LocationManager;
  31. import android.media.MediaScannerConnection;
  32. import android.net.Uri;
  33. import android.nfc.NdefMessage;
  34. import android.nfc.NdefRecord;
  35. import android.nfc.NfcAdapter;
  36. import android.nfc.Tag;
  37. import android.nfc.tech.Ndef;
  38. import android.os.AsyncTask;
  39. import android.os.Build;
  40. import android.os.Bundle;
  41. import android.os.Environment;
  42. import android.os.Handler;
  43. import android.os.Looper;
  44. import android.os.Parcelable;
  45. import android.preference.PreferenceManager;
  46. import android.provider.MediaStore;
  47. import android.provider.Settings;
  48. import android.support.annotation.NonNull;
  49. import android.support.annotation.RequiresApi;
  50. import android.support.design.widget.CoordinatorLayout;
  51. import android.support.design.widget.FloatingActionButton;
  52. import android.support.design.widget.NavigationView;
  53. import android.support.design.widget.TabLayout;
  54. import android.support.v4.content.ContextCompat;
  55. import android.support.v4.content.LocalBroadcastManager;
  56. import android.support.v4.view.GravityCompat;
  57. import android.support.v4.view.ViewPager;
  58. import android.support.v4.widget.DrawerLayout;
  59. import android.support.v7.app.ActionBarDrawerToggle;
  60. import android.support.v7.app.AlertDialog;
  61. import android.support.v7.app.AppCompatActivity;
  62. import android.support.v7.widget.Toolbar;
  63. import android.system.ErrnoException;
  64. import android.text.InputType;
  65. import android.text.TextUtils;
  66. import android.util.Log;
  67. import android.view.Gravity;
  68. import android.view.Menu;
  69. import android.view.MenuItem;
  70. import android.view.SurfaceHolder;
  71. import android.view.View;
  72. import android.widget.AnalogClock;
  73. import android.widget.ArrayAdapter;
  74. import android.widget.Button;
  75. import android.widget.EditText;
  76. import android.widget.ImageView;
  77. import android.widget.LinearLayout;
  78. import android.widget.Spinner;
  79. import android.widget.TextView;
  80. import android.widget.Toast;
  81.  
  82. import com.android.volley.DefaultRetryPolicy;
  83. import com.android.volley.Request;
  84. import com.android.volley.RequestQueue;
  85. import com.android.volley.RetryPolicy;
  86. import com.android.volley.toolbox.StringRequest;
  87. import com.android.volley.toolbox.Volley;
  88. import com.androidadvance.topsnackbar.TSnackbar;
  89. import com.bumptech.glide.Glide;
  90. import com.google.android.gms.maps.MapsInitializer;
  91. import com.google.firebase.auth.FirebaseAuth;
  92. import com.google.firebase.auth.FirebaseAuthUserCollisionException;
  93. import com.google.firebase.auth.FirebaseUser;
  94. import com.google.firebase.iid.FirebaseInstanceId;
  95. import com.google.firebase.messaging.FirebaseMessaging;
  96. import com.gun0912.tedpermission.PermissionListener;
  97. import com.gun0912.tedpermission.TedPermission;
  98. import com.lesjaw.wamonitoring.BuildConfig;
  99. import com.lesjaw.wamonitoring.NetworkRequest;
  100. import com.lesjaw.wamonitoring.R;
  101. import com.lesjaw.wamonitoring.ui.fragment.ChatFrag;
  102. import com.lesjaw.wamonitoring.ui.fragment.LogAlert;
  103. import com.lesjaw.wamonitoring.ui.fragment.Main;
  104. import com.lesjaw.wamonitoring.ui.fragment.TagInfo;
  105. import com.lesjaw.wamonitoring.ui.fragment.Tags;
  106. import com.lesjaw.wamonitoring.utils.AESEncryptionDecryption;
  107. import com.lesjaw.wamonitoring.utils.Config;
  108. import com.lesjaw.wamonitoring.utils.DataPagerAdapter;
  109. import com.lesjaw.wamonitoring.utils.PreferenceHelper;
  110. import com.lesjaw.wamonitoring.utils.Utils;
  111. import com.mancj.slideup.SlideUp;
  112. import com.mancj.slideup.SlideUpBuilder;
  113. import com.muddzdev.styleabletoastlibrary.StyleableToast;
  114. import com.squareup.okhttp.MediaType;
  115. import com.squareup.okhttp.OkHttpClient;
  116. import com.squareup.okhttp.RequestBody;
  117. import com.squareup.okhttp.Response;
  118. import com.theartofdev.edmodo.cropper.CropImageView;
  119.  
  120. import net.gotev.uploadservice.MultipartUploadRequest;
  121. import net.gotev.uploadservice.ServerResponse;
  122. import net.gotev.uploadservice.UploadInfo;
  123. import net.gotev.uploadservice.UploadNotificationConfig;
  124. import net.gotev.uploadservice.UploadStatusDelegate;
  125.  
  126. import org.jetbrains.annotations.NotNull;
  127. import org.json.JSONArray;
  128. import org.json.JSONException;
  129. import org.json.JSONObject;
  130.  
  131. import java.io.ByteArrayOutputStream;
  132. import java.io.File;
  133. import java.io.FileNotFoundException;
  134. import java.io.FileOutputStream;
  135. import java.io.IOException;
  136. import java.io.InputStream;
  137. import java.io.UnsupportedEncodingException;
  138. import java.text.ParseException;
  139. import java.text.SimpleDateFormat;
  140. import java.util.ArrayList;
  141. import java.util.Arrays;
  142. import java.util.Calendar;
  143. import java.util.Date;
  144. import java.util.HashMap;
  145. import java.util.List;
  146. import java.util.Locale;
  147. import java.util.Map;
  148. import java.util.UUID;
  149. import java.util.function.DoubleBinaryOperator;
  150. import java.util.stream.Collectors;
  151.  
  152. import de.hdodenhof.circleimageview.CircleImageView;
  153. import io.ghyeok.stickyswitch.widget.StickySwitch;
  154.  
  155. public class MainActivity extends AppCompatActivity implements LocationListener, NavigationView.OnNavigationItemSelectedListener {
  156.  
  157. private ViewPager mViewPager;
  158. private DataPagerAdapter mDataPagerAdaper;
  159. private TabLayout tabLayout;
  160. private CoordinatorLayout coordinatorLayout;
  161. private SharedPreferences sharedPref;
  162. private PreferenceHelper mPrefHelper;
  163. private FirebaseAuth auth;
  164. private FirebaseAuth.AuthStateListener mAuthListener;
  165. private BroadcastReceiver mRegistrationBroadcastReceiver;
  166. private String companyID, divTrim, mUserName, mDistrict;
  167. private final static int ALL_PERMISSIONS_RESULT = 101;
  168. private String mLevelUser, mEmail;
  169. private NfcAdapter mNfcAdapter;
  170. boolean nfcdevices = false;
  171. public static final String MIME_TEXT_PLAIN = "text/plain";
  172. public static final String TAG = "MainActivity";
  173. boolean isGPS = false;
  174. boolean isNetwork = false;
  175. boolean canGetLocation = true;
  176. private LocationManager locationManager;
  177. private Location loc;
  178. private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100;
  179. private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 30;
  180. private CircleImageView imageView;
  181. private SlideUp slideUp;
  182. private View dim;
  183. private FloatingActionButton fab;
  184. private Bitmap cropped;
  185. private CropImageView mCropImageView;
  186. private static final String IMAGE_DIRECTORY = "/wamonitoring";
  187. private EditText note;
  188. private Bitmap icon;
  189. private String versionName;
  190. private NavigationView navigationView;
  191. private DrawerLayout drawer;
  192. private int backButtonCount, position;
  193. boolean on_tagging = false;
  194. private static final MediaType JSON
  195. = MediaType.parse("application/json; charset=utf-8");
  196. private StyleableToast styleableToast;
  197. private StickySwitch oNoFF;
  198. private ArrayList<String> permissions = new ArrayList<>();
  199. private ArrayList<String> permissionsToRequest;
  200. private ArrayList<String> permissionsRejected = new ArrayList<>();
  201. int firstopen = 0;
  202. String labelAbsen, clock;
  203. Boolean selfie = false;
  204. int distanceInteger;
  205. String logStatus;
  206. String sPublic;
  207. Spinner logBookType;
  208.  
  209. PermissionListener permissionlistener = new PermissionListener() {
  210. @Override
  211. public void onPermissionGranted() {
  212. //Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
  213. }
  214.  
  215. @Override
  216. public void onPermissionDenied(ArrayList<String> deniedPermissions) {
  217. styleableToast = new StyleableToast
  218. .Builder(getBaseContext())
  219. .icon(R.drawable.ic_action_info)
  220. .text("Permission Denied\n" + deniedPermissions.toString())
  221. .textColor(Color.WHITE)
  222. .backgroundColor(Color.BLUE)
  223. .build();
  224. styleableToast.show();
  225. }
  226. };
  227. private Toolbar toolbar;
  228. private ProgressDialog pDialog;
  229. boolean insertRecord = false;
  230.  
  231. @RequiresApi(api = Build.VERSION_CODES.N)
  232. @SuppressLint("SetTextI18n")
  233. @Override
  234. protected void onCreate(Bundle savedInstanceState) {
  235. super.onCreate(savedInstanceState);
  236. setContentView(R.layout.activity_main);
  237. String[] spinnerArray = new String[]{
  238. "low",
  239. "medium",
  240. "high"
  241. };
  242. new TedPermission(getBaseContext())
  243. .setPermissionListener(permissionlistener)
  244. .setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
  245. .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
  246. Manifest.permission.CAMERA, Manifest.permission.NFC, Manifest.permission.MODIFY_AUDIO_SETTINGS,
  247. Manifest.permission.INTERNET, Manifest.permission.READ_EXTERNAL_STORAGE)
  248. .check();
  249.  
  250. coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
  251.  
  252. toolbar = (Toolbar) findViewById(R.id.toolbar);
  253. setSupportActionBar(toolbar);
  254. getSupportActionBar().setTitle(R.string.app_name);
  255.  
  256. MapsInitializer.initialize(this);
  257.  
  258. View sliderView = findViewById(R.id.slideViewMain);
  259. //TextView slidedown = (TextView) findViewById(R.id.textView);
  260. mCropImageView = (CropImageView) findViewById(R.id.imageView2);
  261. note = (EditText) findViewById(R.id.noteEdit);
  262. new OkHttpClient();
  263.  
  264.  
  265. sliderView.setOnClickListener(v -> {
  266. slideUp.hide();
  267. fab.show();
  268. });
  269.  
  270. icon = BitmapFactory.decodeResource(getResources(),
  271. R.drawable.logowam);
  272.  
  273. mCropImageView.setImageBitmap(icon);
  274.  
  275. dim = findViewById(R.id.dim);
  276. fab = (FloatingActionButton) findViewById(R.id.fab);
  277. slideUp = new SlideUpBuilder(sliderView)
  278. .withListeners(new SlideUp.Listener.Events() {
  279. @Override
  280. public void onSlide(float percent) {
  281. dim.setAlpha(1 - (percent / 100));
  282. }
  283.  
  284. @Override
  285. public void onVisibilityChanged(int visibility) {
  286. /*if (visibility == View.GONE) {
  287.  
  288. }*/
  289. }
  290. })
  291. .withStartGravity(Gravity.BOTTOM)
  292. .withLoggingEnabled(false)
  293. .withGesturesEnabled(false)
  294. .withStartState(SlideUp.State.HIDDEN)
  295. .build();
  296.  
  297. fab.setOnClickListener(view -> {
  298. // jika sudah absen
  299. if (mPrefHelper.getLogin().equals("1")) {
  300. slideUp.show();
  301. fab.hide();
  302. // jika belum absen
  303. } else {
  304. styleableToast = new StyleableToast
  305. .Builder(getBaseContext())
  306. .icon(R.drawable.ic_action_info)
  307. .text(String.valueOf("Sorry, you can't create logs when you are not Working"))
  308. .textColor(Color.WHITE)
  309. .backgroundColor(Color.BLUE)
  310. .build();
  311. styleableToast.show();
  312. }
  313. });
  314.  
  315. drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  316. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
  317. this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  318. drawer.addDrawerListener(toggle);
  319. toggle.syncState();
  320.  
  321. navigationView = (NavigationView) findViewById(R.id.nav_view);
  322. View headerView = navigationView.getHeaderView(0);
  323. TextView username = (TextView) headerView.findViewById(R.id.textView);
  324. imageView = (CircleImageView) headerView.findViewById(R.id.img_profile);
  325. oNoFF = (StickySwitch ) headerView.findViewById(R.id.onOff);
  326.  
  327. versionName = BuildConfig.VERSION_NAME;
  328.  
  329. navigationView.setNavigationItemSelectedListener(this);
  330. invalidateOptionsMenu();
  331. //MenuItem nav_version = menu.findItem(R.id.nav_version);
  332. //nav_version.setTitle("Version "+versionName);
  333.  
  334. mPrefHelper = new PreferenceHelper(getApplicationContext());
  335. sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  336. auth = FirebaseAuth.getInstance();
  337. TextView textUrgent = (TextView)findViewById(R.id.text_urgent);
  338. logBookType = (Spinner)findViewById(R.id.log_book_type);
  339. if(mPrefHelper.getLevelUser().equals("3")){
  340. ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>
  341. (this, R.layout.spinner_item_complain,
  342. spinnerArray); //selected item will look like a spinner set from XML
  343. spinnerArrayAdapter.setDropDownViewResource(android.R.layout
  344. .simple_spinner_dropdown_item);
  345. logBookType.setAdapter(spinnerArrayAdapter);
  346. textUrgent.setVisibility(View.VISIBLE);
  347. logBookType.setVisibility(View.VISIBLE);
  348. }else{
  349. textUrgent.setVisibility(View.GONE);
  350. logBookType.setVisibility(View.GONE);
  351. }
  352.  
  353. String logStat = mPrefHelper.getLogin();
  354. if (logStat.equals("1")) {
  355. /*oNoFF.setChecked(true);
  356. oNoFF.setText("Online");*/
  357. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  358.  
  359. } else {
  360. /* oNoFF.setChecked(false);
  361. oNoFF.setText("Offline");*/
  362. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  363.  
  364. }
  365. checkTime();
  366.  
  367. mLevelUser = mPrefHelper.getLevelUser();
  368. mUserName = sharedPref.getString("real_name", "olmatix1");
  369. mDistrict = sharedPref.getString("division", "olmatix1");
  370. companyID = sharedPref.getString("company_id", "olmatix1");
  371.  
  372. mEmail = sharedPref.getString("email", "olmatix1");
  373. String mPass = sharedPref.getString("password", "olmatix1");
  374.  
  375. mAuthListener = firebaseAuth -> {
  376. FirebaseUser user = firebaseAuth.getCurrentUser();
  377. if (user != null) {
  378. // User is signed in
  379. //Log.d("DEBUG", "onAuthStateChanged:signed_in:" + user.getUid() + " email " + user.getEmail());
  380. mPrefHelper.setUserName(mUserName);
  381. mPrefHelper.setUserEmail(user.getEmail());
  382. mPrefHelper.setGoogle(2);
  383. } else {
  384. // User is signed out
  385. //Log.d("DEBUG", "onAuthStateChanged:signed_out");
  386. mPrefHelper.setGoogle(1);
  387. }
  388. // ...
  389. };
  390.  
  391. SharedPreferences.Editor editor = sharedPref.edit();
  392. switch (mLevelUser) {
  393. case "0":
  394. navigationView.getMenu().clear(); //clear old inflated items.
  395. navigationView.inflateMenu(R.menu.activity_main_drawer); //inflate new items.
  396. username.setText(mUserName + "\nAdministrator");
  397. mPrefHelper.setDivName("none");
  398. editor.putString("division","none");
  399. editor.apply();
  400.  
  401. break;
  402. case "1":
  403. navigationView.getMenu().clear(); //clear old inflated items.
  404. navigationView.inflateMenu(R.menu.activity_main_drawer); //inflate new items.
  405. username.setText(mUserName + "\nDivision Head " + mPrefHelper.getDivName());
  406.  
  407. break;
  408. case "3":
  409. navigationView.getMenu().clear(); //clear old inflated items.
  410. navigationView.inflateMenu(R.menu.activity_main_drawer); //inflate new items.
  411. username.setText(mUserName + "\nClient Division" + mPrefHelper.getDivName());
  412.  
  413. break;
  414. case "2":
  415. navigationView.getMenu().clear(); //clear old inflated items.
  416. navigationView.inflateMenu(R.menu.activity_main_drawer); //inflate new items.
  417. username.setText(mUserName + " - " + mPrefHelper.getDivName());
  418.  
  419. break;
  420.  
  421. case "4":
  422. navigationView.getMenu().clear(); //clear old inflated items.
  423. navigationView.inflateMenu(R.menu.activity_main_drawer); //inflate new items.
  424. username.setText(mUserName + "\nGroup Head " + mPrefHelper.getDivName());
  425. // group head ga punya divisi karena dia diatas admin (perusahaan), struktur group head, admin, div head, staff
  426. mPrefHelper.setDivName("none");
  427. editor.putString("division","none");
  428. editor.apply();
  429. break;
  430. }
  431.  
  432. mViewPager = (ViewPager) findViewById(R.id.container);
  433. tabLayout = (TabLayout) findViewById(R.id.tab_layout);
  434. mDataPagerAdaper = new DataPagerAdapter(getSupportFragmentManager());
  435.  
  436. tabLayout.setupWithViewPager(mViewPager);
  437. setupViewPager(mViewPager);
  438.  
  439. RegisterFirebase(mEmail, mPass);
  440.  
  441. locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
  442. isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  443. isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  444.  
  445. mNfcAdapter = NfcAdapter.getDefaultAdapter(MainActivity.this);
  446. if (mNfcAdapter == null) {
  447. // Stop here, we definitely need NFC
  448. if (mLevelUser.equals("2")) {
  449. styleableToast = new StyleableToast
  450. .Builder(getBaseContext())
  451. .icon(R.drawable.ic_action_info)
  452. .text("This device doesn't support NFC.")
  453. .textColor(Color.WHITE)
  454. .backgroundColor(Color.BLUE)
  455. .build();
  456. }
  457. nfcdevices = false;
  458. } else {
  459. if (!mNfcAdapter.isEnabled()) {
  460. styleableToast = new StyleableToast
  461. .Builder(getBaseContext())
  462. .icon(R.drawable.ic_action_info)
  463. .text("NFC disabled.")
  464. .textColor(Color.WHITE)
  465. .backgroundColor(Color.BLUE)
  466. .build();
  467. }
  468. nfcdevices = true;
  469. handleIntent(getIntent());
  470. }
  471.  
  472. mRegistrationBroadcastReceiver = new BroadcastReceiver() {
  473. @Override
  474. public void onReceive(Context context, Intent intent) {
  475.  
  476. Log.d(TAG, "onReceive: " + intent);
  477. // checking for type intent filter
  478. if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
  479. // gcm successfully registered
  480. // now subscribe to `global` topic to receive app wide notification
  481.  
  482. displayFirebaseRegId(mEmail);
  483.  
  484. } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
  485. // new push notification is received
  486. String type = intent.getStringExtra("type");
  487. String message = intent.getStringExtra("message");
  488. String user = intent.getStringExtra("user");
  489. //String time = intent.getStringExtra("timestamp");
  490.  
  491. if (!user.equals(mUserName)) {
  492.  
  493. if (type.equals("0") && position != 3) {
  494. callSnackbar(message + " by " + user);
  495. } else if (type.equals("1")) {
  496. callSnackbar(message + " by " + user);
  497. } else if (type.equals("2")) {
  498. callSnackbar(message + " by " + user);
  499. } else if (type.equals("4")) {
  500. // ini untuk apa ya ?
  501. styleableToast = new StyleableToast
  502. .Builder(getBaseContext())
  503. .icon(R.drawable.ic_action_info)
  504. .text(message + " | " + user)
  505. .textColor(Color.WHITE)
  506. .backgroundColor(Color.BLUE)
  507. .build();
  508. styleableToast.show();
  509. }
  510.  
  511.  
  512. }
  513.  
  514. } else if (intent.getAction().equals(Config.SEND_MESSAGE)) {
  515. // new push notification is received
  516. String message = intent.getStringExtra("message");
  517.  
  518. styleableToast = new StyleableToast
  519. .Builder(getBaseContext())
  520. .icon(R.drawable.ic_action_info)
  521. .text(message)
  522. .textColor(Color.WHITE)
  523. .backgroundColor(Color.BLUE)
  524. .build();
  525. styleableToast.show();
  526.  
  527. }
  528. }
  529. };
  530.  
  531. displayFirebaseRegId(mEmail);
  532.  
  533. tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
  534.  
  535. tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
  536. @Override
  537. public void onTabSelected(TabLayout.Tab tab) {
  538. position = tab.getPosition();
  539. //if (!mLevelUser.equals("2") && position == 2) {
  540. if (position == 2) {
  541. fab.show();
  542. } else {
  543. fab.hide();
  544. slideUp.hide();
  545. }
  546.  
  547. int colorFrom = ((ColorDrawable) toolbar.getBackground()).getColor();
  548. int colorTo = getColorForTab(tab.getPosition());
  549.  
  550. ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
  551. colorAnimation.setDuration(1000);
  552. colorAnimation.addUpdateListener(animator -> {
  553. int color = (int) animator.getAnimatedValue();
  554.  
  555. toolbar.setBackgroundColor(color);
  556. tabLayout.setBackgroundColor(color);
  557.  
  558. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  559. getWindow().setStatusBarColor(color);
  560. }
  561. });
  562. colorAnimation.start();
  563. }
  564.  
  565. @Override
  566. public void onTabUnselected(TabLayout.Tab tab) {
  567.  
  568. }
  569.  
  570. @Override
  571. public void onTabReselected(TabLayout.Tab tab) {
  572.  
  573. }
  574. });
  575.  
  576. getPhotoProfileSdcard(mEmail);
  577.  
  578. fab.hide();
  579.  
  580. updateWidget();
  581.  
  582.  
  583.  
  584. permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
  585. permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
  586. permissionsToRequest = (permissions);
  587.  
  588. if (!isGPS) {
  589. Log.d(TAG, "Connection off");
  590. showSettingsAlert();
  591. getLocation();
  592. } else {
  593. Log.d(TAG, "Connection on");
  594. // check permissions
  595. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  596. if (permissionsToRequest.size() > 0) {
  597. requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
  598. ALL_PERMISSIONS_RESULT);
  599. Log.d(TAG, "Permission requests");
  600. canGetLocation = false;
  601. }
  602. }
  603. }
  604.  
  605.  
  606. oNoFF.setOnSelectedChangeListener(new StickySwitch.OnSelectedChangeListener() {
  607. @RequiresApi(api = Build.VERSION_CODES.N)
  608. @Override
  609. public void onSelectedChange(@NotNull StickySwitch.Direction direction, @NotNull String s) {
  610. /*
  611. if (!isGPS) {
  612. Log.d(TAG, "Connection off");
  613. showSettingsAlert();
  614. getLocation();
  615. } else {
  616. Log.d(TAG, "Connection on");
  617. // check permissions
  618. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  619. if (permissionsToRequest.size() > 0) {
  620. requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
  621. ALL_PERMISSIONS_RESULT);
  622. Log.d(TAG, "Permission requests");
  623. canGetLocation = false;
  624. }
  625. }
  626. }
  627. */
  628. sPublic = s;
  629.  
  630. //Log.d(TAG, "Now Selected : " + direction.name() + ", Current Text : " + s);
  631. if (firstopen != 0) {
  632.  
  633. oNoFF.setEnabled(false);
  634. if (direction.name().equals("RIGHT")) {
  635. labelAbsen = "Do you want absence go to WORK?";
  636. clock = "ClockIn";
  637. } else {
  638. labelAbsen = "Do you want absence go to HOME?";
  639. clock = "ClockOut";
  640.  
  641. }
  642.  
  643.  
  644.  
  645. pDialog = new ProgressDialog(MainActivity.this);
  646. pDialog.setMessage("Doing absence. Please wait...");
  647. pDialog.setCancelable(true);
  648. pDialog.setCanceledOnTouchOutside(false);
  649. pDialog.show();
  650.  
  651. String url = Config.DOMAIN + "wamonitoring/get_working_gps.php";
  652.  
  653. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  654. try {
  655. JSONObject jObject = new JSONObject(response);
  656. String result_code = jObject.getString("success");
  657. if (result_code.equals("1")) {
  658. JSONArray cast = jObject.getJSONArray("employee");
  659.  
  660. for (int i = 0; i < cast.length(); i++) {
  661. JSONObject tags_name = cast.getJSONObject(i);
  662. String working_gps = tags_name.getString("working_gps");
  663.  
  664. if (working_gps.isEmpty()) {
  665. working_gps = "0.0,0.0";
  666. }
  667.  
  668. String locSplit[] = working_gps.split(",");
  669. double locLat = Double.parseDouble(String.valueOf(locSplit[0]));
  670. double locLot = Double.parseDouble(String.valueOf(locSplit[1]));
  671.  
  672.  
  673. getLocation();
  674. double prefLat = mPrefHelper.getPhoneLatitude();
  675. double prefLot = mPrefHelper.getPhoneLongitude();
  676.  
  677.  
  678. final Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
  679. String adString = null;
  680. try {
  681. List<Address> list;
  682. list = geocoder.getFromLocation(prefLat, prefLot, 1);
  683. if (list != null && list.size() > 0) {
  684. Address address = list.get(0);
  685. address.getLocality();
  686.  
  687. if (address.getAddressLine(0) != null)
  688. adString = address.getAddressLine(0);
  689.  
  690. }
  691.  
  692. } catch (final IOException e) {
  693. new Thread(() -> Log.e("DEBUG", "Geocoder ERROR", e)).start();
  694. }
  695.  
  696. Location startPoint = new Location("locationA");
  697. startPoint.setLatitude((locLat));
  698. startPoint.setLongitude((locLot));
  699.  
  700. Location endPoint = new Location("locationB");
  701. endPoint.setLatitude((prefLat));
  702. endPoint.setLongitude((prefLot));
  703.  
  704. double distance = startPoint.distanceTo(endPoint);
  705. int distanceInt = (int) distance;
  706. distanceInteger = distanceInt;
  707.  
  708. Intent intentImage = new Intent(MainActivity.this, UploadFotoAbsence.class);
  709. intentImage.putExtra("labelAbsen",labelAbsen);
  710. intentImage.putExtra("adString",adString);
  711. intentImage.putExtra("distance",Utils.getJarak(distanceInt));
  712.  
  713. if (s.equals("IN")) {
  714. intentImage.putExtra("type", "absence_in");
  715. intentImage.putExtra("log_status", "1");
  716. logStatus = "1";
  717. } else {
  718. intentImage.putExtra("log_status", "2");
  719. intentImage.putExtra("type", "absence_out");
  720. logStatus = "2";
  721. }
  722. startActivityForResult(intentImage,99);
  723.  
  724. /*
  725. AnalogClock jam = new AnalogClock(MainActivity.this);
  726. LinearLayout layout = new LinearLayout(MainActivity.this);
  727. layout.setOrientation(LinearLayout.VERTICAL);
  728. layout.addView(jam);
  729. // layout.addView(photo);
  730.  
  731.  
  732. new AlertDialog.Builder(MainActivity.this)
  733. .setTitle("Absence")
  734. .setIcon(R.mipmap.ic_check_black)
  735. .setMessage(labelAbsen + "\n\nYou are now at " + adString + "\n\nIt's " +
  736. Utils.getJarak(distanceInt) + " from your work location\nAltitude = " + mPrefHelper.getPhoneAltitude()+"\nAccuracy GPS = " + Math.round(mPrefHelper.getAccuracy()) +" m")
  737. .setCancelable(false)
  738. .setView(layout)
  739. .setPositiveButton(clock, (dialog, id) -> {
  740.  
  741. Intent intentImage = new Intent(MainActivity.this, UploadFotoAbsence.class);
  742. if (s.equals("IN")) {
  743. intentImage.putExtra("type", "absence_in");
  744. intentImage.putExtra("log_status", "1");
  745. logStatus = "1";
  746. } else {
  747. intentImage.putExtra("log_status", "2");
  748. intentImage.putExtra("type", "absence_out");
  749. logStatus = "2";
  750. }
  751. startActivityForResult(intentImage,99);
  752.  
  753. })
  754.  
  755. .setNegativeButton("Cancel", (dialog, id) -> {
  756. firstopen = 0;
  757. if (s.equals("IN")) {
  758. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  759. } else {
  760. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  761.  
  762. }
  763. selfie = false;
  764. dialog.dismiss();
  765. firstopen = 1;
  766. pDialog.dismiss();
  767. })
  768.  
  769. .show();
  770. */
  771. oNoFF.setEnabled(true);
  772.  
  773. }
  774.  
  775. } else {
  776. styleableToast = new StyleableToast
  777. .Builder(getBaseContext())
  778. .icon(R.drawable.ic_action_info)
  779. .text("Sorry can't absence temporary, please try again later")
  780. .textColor(Color.WHITE)
  781. .backgroundColor(Color.BLUE)
  782. .build();
  783. styleableToast.show();
  784.  
  785. oNoFF.setEnabled(true);
  786.  
  787.  
  788. }
  789.  
  790. } catch (JSONException e) {
  791. e.printStackTrace();
  792. }
  793.  
  794. }, error -> {
  795. Log.d(TAG, "onErrorResponse: " + error);
  796. if (mPrefHelper.getLogin().equals("1")) {
  797. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  798.  
  799. } else {
  800. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  801.  
  802. }
  803.  
  804. styleableToast = new StyleableToast
  805. .Builder(getBaseContext())
  806. .icon(R.drawable.ic_action_info)
  807. .text(String.valueOf("Network error, try again later"))
  808. .textColor(Color.WHITE)
  809. .backgroundColor(Color.RED)
  810. .build();
  811. styleableToast.show();
  812. oNoFF.setEnabled(true);
  813. pDialog.dismiss();
  814. selfie = false;
  815.  
  816. }) {
  817. protected Map<String, String> getParams() {
  818. Map<String, String> MyData = new HashMap<>();
  819. MyData.put("email", mEmail);
  820. return MyData;
  821. }
  822. };
  823. // Adding request to request queue
  824. NetworkRequest.getInstance(MainActivity.this).addToRequestQueue(jsonObjReq);
  825. }
  826. }
  827. });
  828.  
  829. firstopen =1;
  830.  
  831. }
  832.  
  833. private void checkTime() {
  834. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
  835. SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
  836.  
  837.  
  838. Calendar now;
  839. now = Calendar.getInstance();
  840. now.setTime(new Date());
  841. long phoneTime = now.getTimeInMillis();
  842. long serverTime = mPrefHelper.getServerTime();
  843.  
  844. String phoneNow = simpleDateFormat.format(phoneTime);
  845. String serverNow = simpleDateFormat.format(serverTime);
  846.  
  847. String phoneWaktu = simpleDateFormat1.format(phoneTime);
  848. String serverWaktu = simpleDateFormat1.format(serverTime);
  849.  
  850. Log.d(TAG, "checkTime: "+phoneNow +" "+phoneWaktu+" | "+serverNow+" "+serverWaktu);
  851.  
  852. if (!phoneNow.equals(serverNow)){
  853. StyleableToast styleableToast = new StyleableToast
  854. .Builder(getBaseContext())
  855. .icon(R.drawable.ic_action_info)
  856. .text("Date error, it seems that your phone date is WRONG!, exiting now..")
  857. .textColor(Color.WHITE)
  858. .backgroundColor(Color.RED)
  859. .build();
  860. styleableToast.show();
  861.  
  862. new Handler(Looper.getMainLooper()).postDelayed(this::finish, 4000);
  863. }
  864.  
  865. }
  866.  
  867. private void callSnackbar(String message) {
  868. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, message, TSnackbar.LENGTH_SHORT);
  869. View snackbarView = snackbar.getView();
  870. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  871.  
  872. snackbar.show();
  873. }
  874.  
  875. public int getColorForTab(int position) {
  876. if (position == 0) return ContextCompat.getColor(this, R.color.colorPrimary);
  877. else if (position == 1) return ContextCompat.getColor(this, R.color.indigo);
  878. else if (position == 2) return ContextCompat.getColor(this, R.color.node_title);
  879. else if (position == 3) return ContextCompat.getColor(this, R.color.amberdark);
  880. else return ContextCompat.getColor(this, R.color.grey);
  881. }
  882.  
  883. private void getPhotoProfileSdcard(String email) {
  884. String IMAGE_DIRECTORY = "/wamonitoring";
  885. File wallpaperDirectory = new File(
  886. Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY + "/upload");
  887. File f = new File(wallpaperDirectory, email + ".jpg");
  888. String imageInSD = f.getAbsolutePath();
  889. Glide.with(getBaseContext())
  890. .load(imageInSD)
  891. .into(imageView);
  892. }
  893.  
  894. public void onLoadImageClick(View view) {
  895. startActivityForResult(getPickImageChooserIntent(), 200);
  896. }
  897.  
  898. public void onCropImageClick(View view) {
  899. cropped = mCropImageView.getCroppedImage(1000, 1000);
  900. if (cropped != null)
  901. mCropImageView.setImageBitmap(cropped);
  902. }
  903.  
  904. public void onUploadImageClick(View view) {
  905. String checkText = note.getText().toString();
  906.  
  907. if (checkText.isEmpty()) {
  908. note.setHint("type some word");
  909. } else {
  910. if (cropped != null) {
  911. saveImage(cropped);
  912. slideUp.hide();
  913. note.setText("");
  914. mCropImageView.setImageBitmap(icon);
  915.  
  916.  
  917. } else {
  918. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "You are not cropping the photo, sending text message only?", TSnackbar.LENGTH_LONG);
  919. View snackbarView = snackbar.getView();
  920. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  921. snackbar.setActionTextColor(Color.BLACK);
  922. snackbar.setAction("OK", v -> {
  923. insertAlert(note.getText().toString().trim());
  924. slideUp.hide();
  925. fab.show();
  926. note.setText("");
  927. });
  928. snackbar.show();
  929. }
  930. }
  931. }
  932.  
  933. public Intent getPickImageChooserIntent() {
  934.  
  935. Uri outputFileUri = getCaptureImageOutputUri();
  936.  
  937. List<Intent> allIntents = new ArrayList<>();
  938. PackageManager packageManager = getPackageManager();
  939.  
  940. Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  941. List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
  942. for (ResolveInfo res : listCam) {
  943. Intent intent = new Intent(captureIntent);
  944. intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
  945. intent.setPackage(res.activityInfo.packageName);
  946. if (outputFileUri != null) {
  947. intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
  948. }
  949. allIntents.add(intent);
  950. }
  951.  
  952. Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
  953. galleryIntent.setType("image/*");
  954. List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
  955. for (ResolveInfo res : listGallery) {
  956. Intent intent = new Intent(galleryIntent);
  957. intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
  958. intent.setPackage(res.activityInfo.packageName);
  959. allIntents.add(intent);
  960. }
  961.  
  962. Intent mainIntent = allIntents.get(allIntents.size() - 1);
  963. for (Intent intent : allIntents) {
  964. if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
  965. mainIntent = intent;
  966. break;
  967. }
  968. }
  969. allIntents.remove(mainIntent);
  970.  
  971. Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
  972.  
  973. chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
  974.  
  975. return chooserIntent;
  976. }
  977.  
  978. private Uri getCaptureImageOutputUri() {
  979. Uri outputFileUri = null;
  980. File getImage = getExternalCacheDir();
  981. if (getImage != null) {
  982. outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
  983. }
  984. return outputFileUri;
  985. }
  986.  
  987. public Uri getPickImageResultUri(Intent data) {
  988. boolean isCamera = true;
  989. if (data != null && data.getData() != null) {
  990. String action = data.getAction();
  991. isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
  992. }
  993. return isCamera ? getCaptureImageOutputUri() : data.getData();
  994. }
  995.  
  996. @RequiresApi(api=Build.VERSION_CODES.LOLLIPOP) public boolean isUriRequiresPermissions(Uri uri) {
  997. try {
  998. ContentResolver resolver = getContentResolver();
  999. InputStream stream = resolver.openInputStream(uri);
  1000. stream.close();
  1001. return false;
  1002. } catch (FileNotFoundException e) {
  1003. if (e.getCause() instanceof ErrnoException) {
  1004. return true;
  1005. }
  1006. } catch (Exception ignored) {
  1007. }
  1008. return false;
  1009. }
  1010.  
  1011. @Override
  1012. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  1013. if (data != null) Log.d(TAG, "onActivityResult: " + resultCode + " " + data.getData());
  1014. if(requestCode == 99){
  1015. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  1016. selfie = sharedPref.getBoolean("selfie",true);
  1017. if(selfie){
  1018. absence(logStatus, String.valueOf(distanceInteger));
  1019. }else{
  1020. styleableToast = new StyleableToast
  1021. .Builder(getBaseContext())
  1022. .icon(R.drawable.ic_action_info)
  1023. .text("Sorry can't absence, selfie photo failed!!")
  1024. .textColor(Color.WHITE)
  1025. .backgroundColor(Color.BLUE)
  1026. .build();
  1027. styleableToast.show();
  1028.  
  1029. firstopen = 0;
  1030. if (sPublic.equals("IN")) {
  1031. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  1032. } else {
  1033. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  1034.  
  1035. }
  1036. selfie = false;
  1037. firstopen = 1;
  1038. pDialog.dismiss();
  1039.  
  1040. }
  1041.  
  1042.  
  1043. }else{
  1044.  
  1045. if (resultCode == Activity.RESULT_OK) {
  1046. Uri imageUri = getPickImageResultUri(data);
  1047.  
  1048. //image.setImageURI(imageUri);
  1049. boolean requirePermissions = false;
  1050. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
  1051. checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
  1052. isUriRequiresPermissions(imageUri)) {
  1053.  
  1054. // request permissions and handle the result in onRequestPermissionsResult()
  1055. requirePermissions = true;
  1056. requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
  1057. }
  1058.  
  1059. if (!requirePermissions) {
  1060. mCropImageView.setImageUriAsync(imageUri);
  1061. }
  1062. }
  1063. }
  1064.  
  1065. super.onActivityResult(requestCode, resultCode, data);
  1066. }
  1067.  
  1068. private void displayFirebaseRegId(String mEmail) {
  1069. SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
  1070. String regId = pref.getString("regId", null);
  1071.  
  1072. Log.e("DEBUG", "Firebase reg id: " + regId);
  1073.  
  1074.  
  1075. if (!TextUtils.isEmpty(regId)) {
  1076. //Toast.makeText(getApplicationContext(), "Firebase reg id: " + regId, Toast.LENGTH_LONG).show();
  1077. new FirebaseID(mEmail, regId).execute();
  1078.  
  1079. } else {
  1080. String regid = FirebaseInstanceId.getInstance().getToken();
  1081. Log.e("DEBUG", "onTokenRefresh: " + regid + mEmail);
  1082. new FirebaseID(mEmail, regid).execute();
  1083. //Toast.makeText(getApplicationContext(), "Firebase Reg Id is not received yet! " + regId+ " " + regid, Toast.LENGTH_LONG).show();
  1084. }
  1085. String div = sharedPref.getString("division", "olmatix1");
  1086. divTrim = div.replace(" ", "");
  1087.  
  1088. FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
  1089. FirebaseMessaging.getInstance().subscribeToTopic(companyID);
  1090. FirebaseMessaging.getInstance().subscribeToTopic(companyID + "-" + divTrim);
  1091. if (!mLevelUser.equals("2")) {
  1092. FirebaseMessaging.getInstance().subscribeToTopic(companyID + "-AM");
  1093. }
  1094.  
  1095. }
  1096.  
  1097. public void RegisterFirebase(String email, String password) {
  1098.  
  1099. auth.createUserWithEmailAndPassword(email, password)
  1100. .addOnCompleteListener(MainActivity.this, task -> {
  1101. //Toast.makeText(MainActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
  1102. // If sign in fails, display a message to the user. If sign in succeeds
  1103. // the auth state listener will be notified and logic to handle the
  1104. // signed in user can be handled in the listener.
  1105. if (!task.isSuccessful()) {
  1106. //Toast.makeText(MainActivity.this, "Authentication failed." + task.getException(),
  1107. // Toast.LENGTH_SHORT).show();
  1108. //Log.d("DEBUG", "onComplete: " + task.getException());
  1109. if (task.getException() instanceof FirebaseAuthUserCollisionException) {
  1110. //Toast.makeText(MainActivity.this, "User with this email already exist, trying login to chat now", Toast.LENGTH_SHORT).show();
  1111. auth.signInWithEmailAndPassword(email, password)
  1112. .addOnCompleteListener(MainActivity.this, task1 -> {
  1113. Log.d("DEBUG", "signInWithEmail:onComplete:" + task1.isSuccessful());
  1114. //Toast.makeText(MainActivity.this, "Auth success "+task.isSuccessful(),
  1115. // Toast.LENGTH_SHORT).show();
  1116. mPrefHelper.setGoogle(2);
  1117. // If sign in fails, display a message to the user. If sign in succeeds
  1118. // the auth state listener will be notified and logic to handle the
  1119. // signed in user can be handled in the listener.
  1120. if (!task1.isSuccessful()) {
  1121.  
  1122. styleableToast = new StyleableToast
  1123. .Builder(getBaseContext())
  1124. .icon(R.drawable.ic_upload_error)
  1125. .text("Auth failed")
  1126. .textColor(Color.WHITE)
  1127. .backgroundColor(Color.BLUE)
  1128. .build();
  1129.  
  1130. }
  1131.  
  1132. });
  1133. }
  1134.  
  1135. }
  1136. });
  1137. }
  1138.  
  1139. private void setupViewPager(ViewPager viewPager) {
  1140.  
  1141. if (!mLevelUser.equals("2")) {
  1142. mDataPagerAdaper.addFrag(new Main(), "MAIN");
  1143. mDataPagerAdaper.addFrag(new Tags(), "TAGS");
  1144. mDataPagerAdaper.addFrag(new LogAlert(), "LOGS");
  1145. mDataPagerAdaper.addFrag(new ChatFrag(), "CHATS");
  1146. viewPager.setOffscreenPageLimit(4);
  1147.  
  1148. } else {
  1149. mDataPagerAdaper.addFrag(new Main(), "MAIN");
  1150. mDataPagerAdaper.addFrag(new Tags(), "TAGS");
  1151. mDataPagerAdaper.addFrag(new LogAlert(), "LOGS");
  1152. mDataPagerAdaper.addFrag(new ChatFrag(), "CHATS");
  1153. viewPager.setOffscreenPageLimit(4);
  1154.  
  1155. }
  1156. viewPager.setAdapter(mDataPagerAdaper);
  1157. }
  1158.  
  1159. @Override
  1160. protected void onSaveInstanceState(final Bundle outState) {
  1161. // super.onSaveInstanceState(outState);
  1162. }
  1163.  
  1164. public boolean onPrepareOptionsMenu(Menu menu) {
  1165. menu = navigationView.getMenu();
  1166. menu.findItem(R.id.nav_version).setTitle("Version " + versionName);
  1167. return super.onPrepareOptionsMenu(menu);
  1168. }
  1169.  
  1170. @Override
  1171. public boolean onCreateOptionsMenu(Menu menu) {
  1172. // Inflate the menu; this adds items to the action bar if it is present.
  1173. getMenuInflater().inflate(R.menu.menu_main, menu);
  1174. return true;
  1175. }
  1176.  
  1177. @Override
  1178. public void onStart() {
  1179. super.onStart();
  1180. auth.addAuthStateListener(mAuthListener);
  1181. LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(
  1182. mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION));
  1183.  
  1184. LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(
  1185. mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE));
  1186.  
  1187. LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(
  1188. mRegistrationBroadcastReceiver, new IntentFilter(Config.SEND_MESSAGE));
  1189. }
  1190.  
  1191. @Override
  1192. public void onStop() {
  1193. if (mAuthListener != null) {
  1194. auth.removeAuthStateListener(mAuthListener);
  1195. }
  1196.  
  1197. LocalBroadcastManager.getInstance(getBaseContext()).unregisterReceiver(mRegistrationBroadcastReceiver);
  1198.  
  1199. super.onStop();
  1200. }
  1201.  
  1202. @Override
  1203. protected void onPostResume() {
  1204. super.onPostResume();
  1205. if (mNfcAdapter != null) {
  1206. try {
  1207. setupForegroundDispatch(MainActivity.this, mNfcAdapter);
  1208. } catch (Exception e) {
  1209. Log.e(TAG, "Error starting foreground dispatch", e);
  1210. }
  1211. }
  1212.  
  1213. /*LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(
  1214. mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION));*/
  1215. }
  1216.  
  1217. @Override
  1218. public void onPause() {
  1219. super.onPause();
  1220. Log.d(TAG, "onPause: 2");
  1221. }
  1222.  
  1223. @Override
  1224. protected void onDestroy() {
  1225. super.onDestroy();
  1226. LocalBroadcastManager.getInstance(getBaseContext()).unregisterReceiver(mRegistrationBroadcastReceiver);
  1227. }
  1228.  
  1229. @Override
  1230. public boolean onOptionsItemSelected(MenuItem item) {
  1231.  
  1232. int id = item.getItemId();
  1233.  
  1234. //noinspection SimplifiableIfStatement
  1235. if (id == android.R.id.home) {
  1236. return true;
  1237. }
  1238.  
  1239. if (id == R.id.action_settings) {
  1240. Intent i = new Intent(this, SettingsActivity.class);
  1241. startActivity(i);
  1242. return true;
  1243. }
  1244.  
  1245. if (id == R.id.action_foto) {
  1246. Intent i = new Intent(this, UploadFotoAcivity.class);
  1247. startActivity(i);
  1248. return true;
  1249. }
  1250.  
  1251. if (id == R.id.action_chat) {
  1252. Intent i = new Intent(this, ChatActivityCompany.class);
  1253. i.putExtra("room", companyID);
  1254. startActivity(i);
  1255. return true;
  1256. }
  1257.  
  1258. if (id == R.id.action_logout) {
  1259.  
  1260. final EditText pass = new EditText(MainActivity.this);
  1261. pass.setHint("Type logout password");
  1262. pass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
  1263. pass.setMaxLines(1);
  1264.  
  1265. String divPass;
  1266. if (mPrefHelper.getLevelUser().equals("1")){
  1267. divPass = "none";
  1268. } else {
  1269. divPass = sharedPref.getString("division", "olmatix1");
  1270. }
  1271.  
  1272.  
  1273. LinearLayout layout = new LinearLayout(MainActivity.this);
  1274. layout.setOrientation(LinearLayout.VERTICAL);
  1275. layout.addView(pass);
  1276.  
  1277. new AlertDialog.Builder(MainActivity.this)
  1278. .setTitle("Logout")
  1279. .setIcon(R.drawable.ic_info_black_24dp)
  1280. .setMessage("Do you want to logout?")
  1281. .setView(layout)
  1282. .setPositiveButton("Ok", (dialog, id1) -> {
  1283. Log.d(TAG, "onOptionsItemSelected: "+divPass+" : "+pass.getText().toString().trim());
  1284.  
  1285. String url = Config.DOMAIN + "wamonitoring/get_pass_logout.php";
  1286.  
  1287. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  1288.  
  1289. try {
  1290.  
  1291. JSONObject jObject = new JSONObject(response);
  1292. String result_message = jObject.getString("message");
  1293. String result_code = jObject.getString("success");
  1294.  
  1295. if (result_code.equals("1")) {
  1296.  
  1297. LogOut();
  1298.  
  1299. } else {
  1300. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, result_message,
  1301. TSnackbar.LENGTH_LONG);
  1302. View snackbarView = snackbar.getView();
  1303. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1304. snackbar.setAction("OK", v -> {
  1305.  
  1306. });
  1307. snackbar.setActionTextColor(Color.BLACK);
  1308. snackbar.show();
  1309. }
  1310.  
  1311. } catch (JSONException e) {
  1312. e.printStackTrace();
  1313. }
  1314.  
  1315.  
  1316. }, error -> Log.d(TAG, "onErrorResponse: " + error)) {
  1317. protected Map<String, String> getParams() {
  1318. Map<String, String> MyData = new HashMap<>();
  1319. MyData.put("company_id", companyID);
  1320. MyData.put("division", divPass);
  1321. MyData.put("password", pass.getText().toString().trim());
  1322. MyData.put("email", mEmail);
  1323.  
  1324. return MyData;
  1325. }
  1326. };
  1327.  
  1328. // Adding request to request queue
  1329. NetworkRequest.getInstance(getBaseContext()).addToRequestQueue(jsonObjReq);
  1330. })
  1331.  
  1332. .setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel())
  1333.  
  1334. .show();
  1335.  
  1336. return true;
  1337. }
  1338.  
  1339.  
  1340. return super.onOptionsItemSelected(item);
  1341. }
  1342.  
  1343. private void LogOut() {
  1344. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  1345. SharedPreferences.Editor editor = sharedPref.edit();
  1346. editor.putString("email", "");
  1347. editor.putString("password", "");
  1348. editor.putString("user_name", "John Smith");
  1349. editor.apply();
  1350.  
  1351. FirebaseMessaging.getInstance().unsubscribeFromTopic(Config.TOPIC_GLOBAL);
  1352. FirebaseMessaging.getInstance().unsubscribeFromTopic(companyID);
  1353. FirebaseMessaging.getInstance().unsubscribeFromTopic(companyID + "-" + divTrim);
  1354. if (!mLevelUser.equals("2")) {
  1355. FirebaseMessaging.getInstance().unsubscribeFromTopic(companyID + "-AM");
  1356. }
  1357. auth.signOut();
  1358. mPrefHelper.setGoogle(1);
  1359. mPrefHelper.setLastLog("Last tag log by notification");
  1360. mPrefHelper.setDivisionFull("Empty");
  1361. mPrefHelper.setEmployment("Empty");
  1362. mPrefHelper.setEmployee_status("Empty");
  1363. mPrefHelper.setLogin("2");
  1364.  
  1365. finish();
  1366. }
  1367.  
  1368. @Override
  1369. public void onLocationChanged(Location location) {
  1370.  
  1371. }
  1372.  
  1373. @Override
  1374. public void onStatusChanged(String provider, int status, Bundle extras) {
  1375.  
  1376. }
  1377.  
  1378. @Override
  1379. public void onProviderEnabled(String provider) {
  1380.  
  1381. }
  1382.  
  1383. @Override
  1384. public void onProviderDisabled(String provider) {
  1385.  
  1386. }
  1387.  
  1388. @Override
  1389. public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  1390.  
  1391. // Handle navigation view item clicks here.
  1392. int id = item.getItemId();
  1393. if (id == R.id.nav_create_db) {
  1394. if (!mLevelUser.equals("2")&&!mLevelUser.equals("4")&&!mLevelUser.equals("3")) {
  1395. Intent i = new Intent(getBaseContext(), DBStructureActivity.class);
  1396. startActivity(i);
  1397. } else {
  1398. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Sorry you are not allowed to use this menu", TSnackbar.LENGTH_SHORT);
  1399. View snackbarView = snackbar.getView();
  1400. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  1401. snackbar.show();
  1402. }
  1403. return true;
  1404.  
  1405. }
  1406. if (id == R.id.nav_tag_monitor) {
  1407. if (!mLevelUser.equals("2")) {
  1408. Intent i = new Intent(getBaseContext(), MainDataActivity.class);
  1409. startActivity(i);
  1410. } else {
  1411. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Sorry you are not allowed to use this menu", TSnackbar.LENGTH_SHORT);
  1412. View snackbarView = snackbar.getView();
  1413. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  1414. snackbar.show();
  1415. }
  1416. return true;
  1417.  
  1418. }
  1419. if (id == R.id.nav_track_employee) {
  1420. if (!mLevelUser.equals("2")) {
  1421. Intent i = new Intent(getBaseContext(), TrackEmployeeActivity.class);
  1422. startActivity(i);
  1423. } else {
  1424. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Sorry you are not allowed to use this menu", TSnackbar.LENGTH_SHORT);
  1425. View snackbarView = snackbar.getView();
  1426. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  1427. snackbar.show();
  1428. }
  1429. return true;
  1430.  
  1431. }
  1432. if (id == R.id.nav_employee_db) {
  1433. if (!mLevelUser.equals("2")) {
  1434.  
  1435. Intent i = new Intent(getBaseContext(), ListEmployeeActivity.class);
  1436. startActivity(i);
  1437. } else {
  1438. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Sorry you are not allowed to use this menu", TSnackbar.LENGTH_SHORT);
  1439. View snackbarView = snackbar.getView();
  1440. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  1441. snackbar.show();
  1442. }
  1443. return true;
  1444.  
  1445. }
  1446.  
  1447. if (id == R.id.nav_absence) {
  1448. if (!mLevelUser.equals("2")) {
  1449. Intent i = new Intent(getBaseContext(), MainAbsenActivity.class);
  1450. //i.putExtra("id_fragement", "Absence");
  1451. startActivity(i);
  1452. } else {
  1453. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Sorry you are not allowed to use this menu", TSnackbar.LENGTH_SHORT);
  1454. View snackbarView = snackbar.getView();
  1455. snackbarView.setBackgroundColor(Color.parseColor("#000000"));
  1456. snackbar.show();
  1457. }
  1458. return true;
  1459.  
  1460. }
  1461.  
  1462. if (id == R.id.nav_version) {
  1463. styleableToast = new StyleableToast
  1464. .Builder(getBaseContext())
  1465. .icon(R.drawable.ic_action_info)
  1466. .text("Version " + versionName)
  1467. .textColor(Color.WHITE)
  1468. .backgroundColor(Color.BLUE)
  1469. .build();
  1470. styleableToast.show();
  1471. return true;
  1472.  
  1473. }
  1474.  
  1475. if (id == R.id.nav_about) {
  1476. Intent i = new Intent(this, AboutActivity.class);
  1477. startActivity(i);
  1478. return true;
  1479. }
  1480.  
  1481.  
  1482. if (id == R.id.nav_preferences) {
  1483. Intent i = new Intent(this, SettingsActivity.class);
  1484. startActivity(i);
  1485. return true;
  1486. }
  1487.  
  1488.  
  1489. return false;
  1490. }
  1491.  
  1492. private class FirebaseID extends AsyncTask<Void, Void, Void> {
  1493.  
  1494. String email, fbid;
  1495.  
  1496. FirebaseID(String email, String fbid) {
  1497. this.email = email;
  1498. this.fbid = fbid;
  1499. }
  1500.  
  1501. @Override
  1502. protected void onPreExecute() {
  1503. super.onPreExecute();
  1504. }
  1505.  
  1506. @Override
  1507. protected Void doInBackground(Void... arg0) {
  1508. Log.d("DEBUG", "doInBackground: " + email + " " + fbid);
  1509.  
  1510. RequestQueue MyRequestQueue = Volley.newRequestQueue(getBaseContext());
  1511.  
  1512. String url = "https://olmatix.com/wamonitoring/update_fbid.php";
  1513. StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, response -> {
  1514. try {
  1515.  
  1516. JSONObject jObject = new JSONObject(response);
  1517. //String result_code = jObject.getString("success");
  1518. //Log.d("DEBUG", "doInBackground: " + result_code + " email " + email + " id " + fbid);
  1519. /*if (result_code.equals("1")) {
  1520. //Log.d("DEBUG", "doInBackground: " + result_code + " email " + email + " id " + fbid);
  1521.  
  1522. }*/
  1523.  
  1524. } catch (JSONException e) {
  1525. e.printStackTrace();
  1526. }
  1527.  
  1528. }, error -> Log.d("DEBUG", "onErrorResponse: " + error)) {
  1529. protected Map<String, String> getParams() {
  1530. Map<String, String> MyData = new HashMap<>();
  1531. MyData.put("email", email);
  1532. MyData.put("firebase_id", fbid);
  1533. return MyData;
  1534. }
  1535. };
  1536.  
  1537. // Adding request to request queue
  1538.  
  1539. int socketTimeout = 60000;//30 seconds - change to what you want
  1540. RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
  1541. MyStringRequest.setRetryPolicy(policy);
  1542. MyRequestQueue.add(MyStringRequest);
  1543.  
  1544.  
  1545. return null;
  1546. }
  1547.  
  1548. @Override
  1549. protected void onPostExecute(Void result) {
  1550. super.onPostExecute(result);
  1551.  
  1552. }
  1553. }
  1554.  
  1555. @Override
  1556. protected void onNewIntent(Intent intent) {
  1557. super.onNewIntent(intent);
  1558. if (mNfcAdapter != null) {
  1559. handleIntent(intent);
  1560. }
  1561.  
  1562. }
  1563.  
  1564. private void handleIntent(Intent intent) {
  1565. String action = intent.getAction();
  1566. if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
  1567.  
  1568. String type = intent.getType();
  1569. if (MIME_TEXT_PLAIN.equals(type)) {
  1570.  
  1571. Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  1572. new NdefReaderTask().execute(tag);
  1573.  
  1574. } else {
  1575. Log.d("DEBUG", "Wrong mime type: " + type);
  1576. }
  1577. } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
  1578.  
  1579. // In case we would still use the Tech Discovered Intent
  1580. Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  1581. String[] techList = tag.getTechList();
  1582. String searchedTech = Ndef.class.getName();
  1583.  
  1584. for (String tech : techList) {
  1585. if (searchedTech.equals(tech)) {
  1586. new NdefReaderTask().execute(tag);
  1587. break;
  1588. }
  1589. }
  1590. }
  1591. }
  1592.  
  1593. private class NdefReaderTask extends AsyncTask<Tag, Void, String> {
  1594.  
  1595. @Override
  1596. protected String doInBackground(Tag... params) {
  1597. Tag tag = params[0];
  1598.  
  1599. Ndef ndef = Ndef.get(tag);
  1600. if (ndef == null) {
  1601. // NDEF is not supported by this Tag.
  1602. return null;
  1603. }
  1604.  
  1605. NdefMessage ndefMessage = ndef.getCachedNdefMessage();
  1606.  
  1607. NdefRecord[] records = ndefMessage.getRecords();
  1608. for (NdefRecord ndefRecord : records) {
  1609. if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
  1610. try {
  1611. return readText(ndefRecord);
  1612. } catch (UnsupportedEncodingException e) {
  1613. Log.e(TAG, "Unsupported Encoding", e);
  1614. }
  1615. }
  1616. }
  1617.  
  1618. return null;
  1619. }
  1620.  
  1621. private String readText(NdefRecord record) throws UnsupportedEncodingException {
  1622. /*
  1623. * See NFC forum specification for "Text Record Type Definition" at 3.2.1
  1624. *
  1625. * http://www.nfc-forum.org/specs/
  1626. *
  1627. * bit_7 defines encoding
  1628. * bit_6 reserved for future use, must be 0
  1629. * bit_5..0 length of IANA language code
  1630. */
  1631.  
  1632. byte[] payload = record.getPayload();
  1633.  
  1634. // Get the Text Encoding
  1635. String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
  1636.  
  1637. // Get the Language Code
  1638. int languageCodeLength = payload[0] & 51;
  1639.  
  1640. // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
  1641. // e.g. "en"
  1642.  
  1643. // Get the Text
  1644. return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
  1645. }
  1646.  
  1647. @Override
  1648. protected void onPostExecute(String result) {
  1649. if (result != null) {
  1650.  
  1651. Log.d(TAG, "onPostExecute NFC: " + result);
  1652. String result1 = "";
  1653. try {
  1654. result1 = AESEncryptionDecryption.decrypt(result);
  1655. } catch (Exception e) {
  1656. e.printStackTrace();
  1657. }
  1658.  
  1659. Log.d(TAG, "onPostExecute NFC after decrypt: " + result1);
  1660.  
  1661. try {
  1662. JSONObject jObject = new JSONObject(result1);
  1663. //String result_name = jObject.getString("name");
  1664. //String result_division = jObject.getString("division");
  1665. String result_tagID = jObject.getString("code");
  1666. // String result_loc = jObject.getString("loc");
  1667. getTags(result_tagID);
  1668. /*Log.d(TAG, "handleResult: " + mprefDivName + ":" + result_division);
  1669.  
  1670. if (mprefDivName.equals(result_division)) {
  1671. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "tag name : " + result_name + "\ndivision : " + result_division, TSnackbar.LENGTH_INDEFINITE);
  1672. View snackbarView = snackbar.getView();
  1673. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1674. snackbar.setAction("OK", v -> {
  1675. // get location
  1676. getLocation();
  1677. Log.d(TAG, "split location: " + result_loc);
  1678.  
  1679. pDialog = new ProgressDialog(MainActivity.this);
  1680. pDialog.setMessage("Validating. Please wait...");
  1681. pDialog.setCancelable(true);
  1682. pDialog.setCanceledOnTouchOutside(false);
  1683. pDialog.show();
  1684.  
  1685. String locSplit[] = result_loc.split(",");
  1686. String locLat = locSplit[0];
  1687. String locLot = locSplit[1];
  1688.  
  1689. Log.d(TAG, "split location: " + locLat + ":" + locLot);
  1690. getTags(result_tagID, locLat, locLot);
  1691. });
  1692. snackbar.setActionTextColor(Color.BLACK);
  1693. snackbar.show();
  1694. } else if (mprefDivName.equals("none")) {
  1695. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "tag name : " + result_name + "\ndivision : " + result_division, TSnackbar.LENGTH_INDEFINITE);
  1696. View snackbarView = snackbar.getView();
  1697. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1698. snackbar.setAction("OK", v -> {
  1699. // get location
  1700. /*getLocation();
  1701. Log.d(TAG, "split location: " + result_loc);
  1702.  
  1703. pDialog = new ProgressDialog(MainActivity.this);
  1704. pDialog.setMessage("Validating. Please wait...");
  1705. pDialog.setCancelable(true);
  1706. pDialog.setCanceledOnTouchOutside(false);
  1707. pDialog.show();
  1708.  
  1709. String locSplit[] = result_loc.split(",");
  1710. String locLat = locSplit[0];
  1711. String locLot = locSplit[1];
  1712.  
  1713. Log.d(TAG, "split location: " + locLat + ":" + locLot);
  1714. getTags(result_tagID, locLat, locLot);
  1715. });
  1716. snackbar.setActionTextColor(Color.BLACK);
  1717. snackbar.show();
  1718. } else {
  1719. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "You are not allowed to tag this checkpoint" +
  1720. "", TSnackbar.LENGTH_INDEFINITE);
  1721. View snackbarView = snackbar.getView();
  1722. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1723. snackbar.setAction("OK", v -> {
  1724. getLocation();
  1725.  
  1726. });
  1727. snackbar.setActionTextColor(Color.BLACK);
  1728. snackbar.show();*/
  1729. //}*/
  1730.  
  1731.  
  1732. } catch (JSONException e) {
  1733. e.printStackTrace();
  1734. }
  1735.  
  1736. }
  1737. }
  1738. }
  1739.  
  1740. public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
  1741. final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
  1742. intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  1743.  
  1744. final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
  1745.  
  1746. IntentFilter[] filters = new IntentFilter[1];
  1747. String[][] techList = new String[][]{};
  1748.  
  1749. // Notice that this is the same filter as in our manifest.
  1750. filters[0] = new IntentFilter();
  1751. filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
  1752. filters[0].addCategory(Intent.CATEGORY_DEFAULT);
  1753. try {
  1754. filters[0].addDataType(MIME_TEXT_PLAIN);
  1755. } catch (IntentFilter.MalformedMimeTypeException e) {
  1756. throw new RuntimeException("Check your mime type.");
  1757. }
  1758.  
  1759. adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
  1760. }
  1761.  
  1762. /*public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
  1763. adapter.disableForegroundDispatch(activity);
  1764. }*/
  1765.  
  1766. private void getLocation() {
  1767. try {
  1768. if (canGetLocation) {
  1769. Log.d(TAG, "Can get location");
  1770. if (isGPS) {
  1771. // from GPS
  1772. Log.d(TAG, "GPS on");
  1773. locationManager.requestLocationUpdates(
  1774. LocationManager.GPS_PROVIDER,
  1775. MIN_TIME_BW_UPDATES,
  1776. MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
  1777.  
  1778. if (locationManager != null) {
  1779. loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  1780. if (loc != null)
  1781.  
  1782.  
  1783. updateUI(loc);
  1784. }
  1785. } else if (isNetwork) {
  1786. // from Network Provider
  1787. Log.d(TAG, "NETWORK_PROVIDER on");
  1788. locationManager.requestLocationUpdates(
  1789. LocationManager.NETWORK_PROVIDER,
  1790. MIN_TIME_BW_UPDATES,
  1791. MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
  1792. if (locationManager != null) {
  1793. loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  1794. if (loc != null)
  1795. updateUI(loc);
  1796. }
  1797. } else {
  1798. loc.setLatitude(0);
  1799. loc.setLongitude(0);
  1800. updateUI(loc);
  1801. }
  1802. } else {
  1803. Log.d(TAG, "Can't get location");
  1804. }
  1805. } catch (SecurityException e) {
  1806. e.printStackTrace();
  1807. }
  1808. }
  1809.  
  1810. private void updateUI(Location loc) {
  1811. //loc.getAccuracy();
  1812.  
  1813. Log.d("TAG","ACCURACY" + loc.getAccuracy());
  1814.  
  1815. String lat = (Double.toString(loc.getLatitude()));
  1816. String lot = (Double.toString(loc.getLongitude()));
  1817. String alt = (Double.toString(loc.getAltitude()));
  1818.  
  1819. int a = Math.round(loc.getAccuracy());
  1820. String acc = (Integer.toString(a));
  1821. //tvTime.setText(DateFormat.getTimeInstance().format(loc.getTime()));
  1822.  
  1823. final PreferenceHelper mPrefHelper = new PreferenceHelper(getApplicationContext());
  1824. mPrefHelper.setPhoneLatitude(Double.parseDouble(lat));
  1825. mPrefHelper.setPhoneLongitude(Double.parseDouble(lot));
  1826. mPrefHelper.setPhoneAltitude(Double.parseDouble(alt));
  1827. mPrefHelper.setAccuracy(Double.parseDouble(acc));
  1828. }
  1829.  
  1830. @Override
  1831. public void onBackPressed() {
  1832.  
  1833. int tabpos = tabLayout.getSelectedTabPosition();
  1834. if (tabpos == 3) {
  1835. if (drawer.isDrawerOpen(GravityCompat.START)) {
  1836. drawer.closeDrawer(GravityCompat.START);
  1837. } else {
  1838. mViewPager.setCurrentItem(2);
  1839. }
  1840. } else if (tabpos == 2) {
  1841. if (drawer.isDrawerOpen(GravityCompat.START)) {
  1842. drawer.closeDrawer(GravityCompat.START);
  1843. } else {
  1844. mViewPager.setCurrentItem(1);
  1845. }
  1846. } else if (tabpos == 1) {
  1847. if (drawer.isDrawerOpen(GravityCompat.START)) {
  1848. drawer.closeDrawer(GravityCompat.START);
  1849. } else {
  1850. mViewPager.setCurrentItem(0);
  1851. }
  1852. } else if (tabpos == 0) {
  1853. if (drawer.isDrawerOpen(GravityCompat.START)) {
  1854. drawer.closeDrawer(GravityCompat.START);
  1855. } else {
  1856. if (backButtonCount >= 1) {
  1857.  
  1858. finish();
  1859. //System.exit(0);
  1860. } else {
  1861. TSnackbar snackbar = TSnackbar.make((coordinatorLayout), "You are exiting " + getResources().getString(R.string.app_name)
  1862. , TSnackbar.LENGTH_LONG);
  1863. View snackbarView = snackbar.getView();
  1864. snackbar.setIconRight(R.mipmap.logo, 24);
  1865. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1866. snackbar.show();
  1867.  
  1868. backButtonCount++;
  1869. }
  1870.  
  1871.  
  1872. }
  1873. }
  1874. //super.onBackPressed();
  1875.  
  1876. }
  1877.  
  1878. private void getTags(String tgid) {
  1879.  
  1880. //String tag_json_obj = "getTags";
  1881.  
  1882. Log.d(TAG, "getTags: " + tgid);
  1883.  
  1884. String url = Config.DOMAIN + "wamonitoring/get_tags_data.php";
  1885.  
  1886. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  1887. String tag_location = null, division_name = null;
  1888.  
  1889. try {
  1890.  
  1891. JSONObject jObject = new JSONObject(response);
  1892. //String result_message = jObject.getString("message");
  1893. String result_code = jObject.getString("success");
  1894.  
  1895. if (result_code.equals("1")) {
  1896. JSONArray cast = jObject.getJSONArray("tags");
  1897. for (int i = 0; i < cast.length(); i++) {
  1898.  
  1899. JSONObject tags_name = cast.getJSONObject(i);
  1900. tag_location = tags_name.getString("tag_location");
  1901. division_name = tags_name.getString("division_name");
  1902. }
  1903.  
  1904. String mprefDivName = mPrefHelper.getDivName();
  1905. String mprefDivName1 = sharedPref.getString("division", "jakarta");
  1906.  
  1907. //Log.d(TAG, "getTags: " + mprefDivName + " " + division_name);
  1908. boolean executeTags;
  1909. //Log.d(TAG, "getTags1: " + executeTags);
  1910. executeTags = mprefDivName.equals(division_name) || mprefDivName1.equals("none");
  1911.  
  1912. if (executeTags) {
  1913. //Log.d(TAG, "getTags3: " + executeTags);
  1914. pDialog = new ProgressDialog(MainActivity.this);
  1915. pDialog.setMessage("Validating. Please wait...");
  1916. pDialog.setCancelable(true);
  1917. pDialog.setCanceledOnTouchOutside(false);
  1918. pDialog.show();
  1919.  
  1920. getLocation();
  1921. String locSplit[] = tag_location.split(",");
  1922. String locLat = locSplit[0];
  1923. String locLot = locSplit[1];
  1924. if (!on_tagging) {
  1925. ValidateTags(tgid, locLat, locLot);
  1926. on_tagging = true;
  1927.  
  1928. }
  1929.  
  1930. } else {
  1931. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "You are not allowed to tag this checkpoint" +
  1932. "", TSnackbar.LENGTH_INDEFINITE);
  1933. View snackbarView = snackbar.getView();
  1934. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1935. snackbar.setAction("OK", v -> getLocation());
  1936. snackbar.setActionTextColor(Color.BLACK);
  1937. snackbar.show();
  1938.  
  1939. }
  1940.  
  1941. } else {
  1942.  
  1943. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "Tag checkpoint is not REGISTERED, contact ADMIN",
  1944. TSnackbar.LENGTH_LONG);
  1945. View snackbarView = snackbar.getView();
  1946. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  1947. snackbar.setAction("OK", v -> {
  1948.  
  1949. });
  1950. snackbar.setActionTextColor(Color.BLACK);
  1951. snackbar.show();
  1952. }
  1953.  
  1954. } catch (JSONException e) {
  1955. e.printStackTrace();
  1956. }
  1957.  
  1958.  
  1959. }, error -> {
  1960. Log.d(TAG, "onErrorResponse: " + error);
  1961. StyleableToast styleableToast = new StyleableToast
  1962. .Builder(getBaseContext())
  1963. .icon(R.drawable.ic_action_info)
  1964. .text("Network error, try again later")
  1965. .textColor(Color.WHITE)
  1966. .backgroundColor(Color.RED)
  1967. .build();
  1968. styleableToast.show();
  1969. pDialog.dismiss();
  1970. on_tagging = false;
  1971.  
  1972. })
  1973.  
  1974. {
  1975. protected Map<String, String> getParams() {
  1976. Map<String, String> MyData = new HashMap<>();
  1977. MyData.put("tid", tgid);
  1978.  
  1979. return MyData;
  1980. }
  1981. };
  1982.  
  1983. // Adding request to request queue
  1984. NetworkRequest.getInstance(this).addToRequestQueue(jsonObjReq);
  1985.  
  1986. }
  1987.  
  1988. private void ValidateTags(String tgid, String tgLat, String tgLot) {
  1989.  
  1990. //String tag_json_obj = "validateTags";
  1991. String mCompanyID = sharedPref.getString("company_id", "olmatix1");
  1992. String mEmail = sharedPref.getString("email", "olmatix1");
  1993.  
  1994. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
  1995. String tgl1 = df.format(Calendar.getInstance().getTime());
  1996.  
  1997. String url = Config.DOMAIN + "wamonitoring/validate_tags_before_sending.php";
  1998.  
  1999. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  2000.  
  2001. try {
  2002.  
  2003. JSONObject jObject = new JSONObject(response);
  2004. //String result_message = jObject.getString("message");
  2005. String result_code = jObject.getString("success");
  2006.  
  2007. if (result_code.equals("1")) {
  2008.  
  2009. JSONArray cast = jObject.getJSONArray("tags");
  2010. String jam = null, tgl = null;
  2011. for (int i = 0; i < cast.length(); i++) {
  2012.  
  2013. JSONObject tags_name = cast.getJSONObject(i);
  2014. tgl = tags_name.getString("tgl");
  2015. jam = tags_name.getString("jam");
  2016.  
  2017. }
  2018.  
  2019. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH );
  2020. String dateNow = simpleDateFormat.format(Calendar.getInstance().getTime());
  2021.  
  2022. Log.d(TAG, "data: " + tgl + dateNow);
  2023.  
  2024. SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm:ss",Locale.ENGLISH);
  2025. Date startDate = null, endDate = null;
  2026. try {
  2027. String jamNow = simpleDateFormat1.format(Calendar.getInstance().getTime());
  2028. startDate = simpleDateFormat1.parse(jam);
  2029. endDate = simpleDateFormat1.parse(jamNow);
  2030.  
  2031. } catch (ParseException e) {
  2032. e.printStackTrace();
  2033. }
  2034.  
  2035. long difference = endDate.getTime() - startDate.getTime();
  2036.  
  2037. Log.d(TAG, "time difference: " + difference);
  2038.  
  2039. Date dateMax = null, dateMin = null;
  2040. if (difference < 0) {
  2041. try {
  2042. dateMax = simpleDateFormat1.parse("24:00");
  2043. dateMin = simpleDateFormat1.parse("00:00");
  2044. } catch (ParseException e) {
  2045. e.printStackTrace();
  2046. }
  2047.  
  2048. difference = (dateMax.getTime() - startDate.getTime()) + (endDate.getTime() - dateMin.getTime());
  2049. }
  2050. int days = (int) (difference / (1000 * 60 * 60 * 24));
  2051. int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
  2052. int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
  2053. Log.i("log_tag", "Hours: " + hours + ", Mins: " + min);
  2054.  
  2055.  
  2056. if (hours == 0 && min <= 10) {
  2057.  
  2058. if (tgl.equals(dateNow)) {
  2059. pDialog.cancel();
  2060. on_tagging = false;
  2061.  
  2062. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "You just Tag this tag " + min + " minute ago",
  2063. TSnackbar.LENGTH_INDEFINITE);
  2064. View snackbarView = snackbar.getView();
  2065. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  2066. snackbar.setAction("OK", v -> {
  2067.  
  2068. });
  2069. snackbar.setActionTextColor(Color.BLACK);
  2070. snackbar.show();
  2071.  
  2072. } else {
  2073. if (!insertRecord){
  2074. InsertTags(tgid, tgLat, tgLot);
  2075.  
  2076. }
  2077. }
  2078. } else {
  2079. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, "You Tag this tag " + hours + " hours "
  2080. + min + " minute ago",
  2081. TSnackbar.LENGTH_INDEFINITE);
  2082. View snackbarView = snackbar.getView();
  2083. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  2084. snackbar.setAction("OK", v -> {
  2085.  
  2086. });
  2087. snackbar.setActionTextColor(Color.BLACK);
  2088. snackbar.show();
  2089. if (!insertRecord) {
  2090.  
  2091. InsertTags(tgid, tgLat, tgLot);
  2092. }
  2093.  
  2094. }
  2095.  
  2096.  
  2097. } else {
  2098. if (!insertRecord) {
  2099. InsertTags(tgid, tgLat, tgLot);
  2100. }
  2101.  
  2102. }
  2103.  
  2104. } catch (JSONException e) {
  2105. e.printStackTrace();
  2106. }
  2107.  
  2108. }, error -> Log.d(TAG, "onErrorResponse: " + error)) {
  2109. protected Map<String, String> getParams() {
  2110. Map<String, String> MyData = new HashMap<>();
  2111. MyData.put("tid", tgid);
  2112. MyData.put("email", mEmail);
  2113. MyData.put("company_id", mCompanyID);
  2114. MyData.put("tgl", tgl1);
  2115.  
  2116. return MyData;
  2117. }
  2118. };
  2119.  
  2120. // Adding request to request queue
  2121. NetworkRequest.getInstance(this).addToRequestQueue(jsonObjReq);
  2122.  
  2123. }
  2124.  
  2125. private void InsertTags(String tgid, String tgLat, String tgLot) {
  2126.  
  2127. insertRecord = true;
  2128. String mCompanyID = sharedPref.getString("company_id", "olmatix1");
  2129. String mEmployee_name = sharedPref.getString("real_name", "olmatix1");
  2130. //String mDivision = sharedPref.getString("division", "olmatix1");
  2131.  
  2132. String mEmail = sharedPref.getString("email", "olmatix1");
  2133. String mLat = String.valueOf(mPrefHelper.getPhoneLatitude());
  2134. String mLot = String.valueOf(mPrefHelper.getPhoneLongitude());
  2135.  
  2136. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
  2137. String tgl = df.format(Calendar.getInstance().getTime());
  2138.  
  2139. SimpleDateFormat df1 = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
  2140. String jam = df1.format(Calendar.getInstance().getTime());
  2141.  
  2142.  
  2143. Location startPoint = new Location("locationA");
  2144. startPoint.setLatitude(Double.parseDouble(tgLat));
  2145. startPoint.setLongitude(Double.parseDouble(tgLot));
  2146.  
  2147. Location endPoint = new Location("locationA");
  2148. endPoint.setLatitude(Double.parseDouble(mLat));
  2149. endPoint.setLongitude(Double.parseDouble(mLot));
  2150.  
  2151. double distance = startPoint.distanceTo(endPoint);
  2152. int distanceInt = (int) distance;
  2153.  
  2154. String url = Config.DOMAIN + "wamonitoring/insert_tag_record.php";
  2155.  
  2156. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  2157.  
  2158. try {
  2159.  
  2160.  
  2161. JSONObject jObject = new JSONObject(response);
  2162. String result_code = jObject.getString("success");
  2163. String result_message = jObject.getString("message");
  2164.  
  2165. if (result_code.equals("1")) {
  2166. sendNotification(mCompanyID, mPrefHelper.getDivName(), mEmployee_name, "TAGS");
  2167.  
  2168. /* pDialog.cancel();
  2169. on_tagging = false;*/
  2170.  
  2171. }
  2172.  
  2173. TSnackbar snackbar = TSnackbar.make(coordinatorLayout, result_message, TSnackbar.LENGTH_INDEFINITE);
  2174. View snackbarView = snackbar.getView();
  2175. snackbarView.setBackgroundColor(Color.parseColor("#FF4081"));
  2176. snackbar.setAction("OK", v -> {
  2177.  
  2178. });
  2179. snackbar.setActionTextColor(Color.BLACK);
  2180. snackbar.show();
  2181. pDialog.cancel();
  2182. on_tagging = false;
  2183.  
  2184. Intent intent = new Intent("tags");
  2185. intent.putExtra("notify", "Checklist update success");
  2186. LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
  2187. insertRecord = true;
  2188.  
  2189.  
  2190. } catch (JSONException e) {
  2191. e.printStackTrace();
  2192. insertRecord = true;
  2193.  
  2194. }
  2195.  
  2196. }, error -> Log.d(TAG, "onErrorResponse: " + error)) {
  2197. protected Map<String, String> getParams() {
  2198. Map<String, String> MyData = new HashMap<>();
  2199. MyData.put("tid", tgid);
  2200. MyData.put("company_id", mCompanyID);
  2201. MyData.put("employee_name", mEmployee_name);
  2202. MyData.put("email", mEmail);
  2203. MyData.put("latitude", mLat);
  2204. MyData.put("longitude", mLot);
  2205. MyData.put("range_loc", String.valueOf(distanceInt));
  2206. MyData.put("tgl", String.valueOf(tgl));
  2207. MyData.put("jam", String.valueOf(jam));
  2208.  
  2209. return MyData;
  2210. }
  2211. };
  2212.  
  2213. // Adding request to request queue
  2214. NetworkRequest.getInstance(this).addToRequestQueue(jsonObjReq);
  2215.  
  2216. }
  2217.  
  2218. public String saveImage(Bitmap myBitmap) {
  2219. ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  2220. myBitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
  2221. File wallpaperDirectory = new File(
  2222. Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY + "/notice");
  2223. // have the object build the directory structure, if needed.
  2224. if (!wallpaperDirectory.exists()) {
  2225. wallpaperDirectory.mkdirs();
  2226. }
  2227.  
  2228. try {
  2229.  
  2230. Calendar now;
  2231. now = Calendar.getInstance();
  2232. now.setTime(new Date());
  2233. now.getTimeInMillis();
  2234.  
  2235. File f = new File(wallpaperDirectory, now.getTimeInMillis() + ".jpg");
  2236. f.createNewFile();
  2237. FileOutputStream fo = new FileOutputStream(f);
  2238. fo.write(bytes.toByteArray());
  2239. MediaScannerConnection.scanFile(this,
  2240. new String[]{f.getPath()},
  2241. new String[]{"image/jpeg"}, null);
  2242. fo.close();
  2243. Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
  2244.  
  2245. new uploadImg(f.getAbsolutePath(), note.getText().toString(), now.getTimeInMillis()).execute();
  2246.  
  2247. return f.getAbsolutePath();
  2248. } catch (IOException e1) {
  2249. e1.printStackTrace();
  2250. }
  2251. return "";
  2252. }
  2253.  
  2254. private class uploadImg extends AsyncTask<Void, Void, Void> {
  2255. String img, notes;
  2256. long millis;
  2257.  
  2258. uploadImg(String img, String notes, long millis) {
  2259. this.img = img;
  2260. this.notes = notes;
  2261. this.millis = millis;
  2262.  
  2263. }
  2264.  
  2265. @Override
  2266. protected void onPreExecute() {
  2267. super.onPreExecute();
  2268. }
  2269.  
  2270. @Override
  2271. protected Void doInBackground(Void... arg0) {
  2272. String mEmail = sharedPref.getString("email", "olmatix1");
  2273. String url = "https://olmatix.com/wamonitoring/upload_panic_log_message.php";
  2274. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
  2275. String tgl = df.format(Calendar.getInstance().getTime());
  2276. String type;
  2277. if(mPrefHelper.getLevelUser().equals("3")){
  2278. type = "2";
  2279. }else{
  2280. type = "1";
  2281. }
  2282. try {
  2283. String uploadId = UUID.randomUUID().toString();
  2284. new MultipartUploadRequest(MainActivity.this, uploadId, url)
  2285. .addFileToUpload(img, "image") //Adding file
  2286. .addParameter("name", mEmail) //Adding text parameter to the request
  2287. .addParameter("employee_name", mUserName) //Adding text parameter to the request
  2288. .addParameter("type", type) //Adding text parameter to the request
  2289. .addParameter("company_id", companyID) //Adding text parameter to the request
  2290. .addParameter("date_created_panic", tgl) //Adding text parameter to the request
  2291. .addParameter("notes", notes) //Adding text parameter to the request
  2292. .addParameter("millis", String.valueOf(millis)) //Adding text parameter to the request
  2293. // latitude as a level complain
  2294. .addParameter("latitude", String.valueOf(logBookType.getSelectedItemPosition()+1)) //Adding text parameter to the request
  2295.  
  2296. .setNotificationConfig(new UploadNotificationConfig())
  2297. .setMaxRetries(2)
  2298. .setDelegate(new UploadStatusDelegate() {
  2299. @Override
  2300. public void onProgress(Context context, UploadInfo uploadInfo) {
  2301.  
  2302. }
  2303.  
  2304. @Override
  2305. public void onError(Context context, UploadInfo uploadInfo, ServerResponse serverResponse, Exception exception) {
  2306.  
  2307. }
  2308.  
  2309. @Override
  2310. public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
  2311. //Toast.makeText(getBaseContext(), "Upload complete", Toast.LENGTH_SHORT).show();
  2312.  
  2313. Intent pushNotification = new Intent(Config.SEND_NOTICE);
  2314. pushNotification.putExtra("message", "sending notice");
  2315. LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(pushNotification);
  2316. }
  2317.  
  2318. @Override
  2319. public void onCancelled(Context context, UploadInfo uploadInfo) {
  2320.  
  2321. }
  2322. })
  2323. .startUpload(); //Starting the upload
  2324.  
  2325. } catch (Exception exc) {
  2326. //Toast.makeText(MainActivity.this, exc.getMessage(), Toast.LENGTH_SHORT).show();
  2327. }
  2328.  
  2329.  
  2330. return null;
  2331. }
  2332.  
  2333. @Override
  2334. protected void onPostExecute(Void result) {
  2335. super.onPostExecute(result);
  2336. }
  2337.  
  2338. }
  2339.  
  2340. private void insertAlert(String note) {
  2341.  
  2342. String mCompanyID = sharedPref.getString("company_id", "olmatix1");
  2343. String mEmployeeName = sharedPref.getString("real_name", "olmatix1");
  2344. String mEmail = sharedPref.getString("email", "olmatix1");
  2345. String mDivision = sharedPref.getString("division", "olmatix1");
  2346.  
  2347. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
  2348. String tgl = df.format(Calendar.getInstance().getTime());
  2349.  
  2350. //String tag_json_obj = "insertAlert";
  2351.  
  2352. String url = Config.DOMAIN + "wamonitoring/insert_alert_message.php";
  2353.  
  2354. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  2355. try {
  2356.  
  2357. JSONObject jObject = new JSONObject(response);
  2358. String result_code = jObject.getString("success");
  2359. if (result_code.equals("1")) {
  2360. //Log.d(TAG, "location insert success ");
  2361.  
  2362. Intent pushNotification = new Intent(Config.SEND_NOTICE);
  2363. pushNotification.putExtra("message", "sending notice");
  2364. LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(pushNotification);
  2365.  
  2366. } else {
  2367. Log.d(TAG, "location insert fail ");
  2368.  
  2369. }
  2370.  
  2371. } catch (JSONException e) {
  2372. e.printStackTrace();
  2373. }
  2374.  
  2375. }, error -> {
  2376. Log.d(TAG, "onErrorResponse: " + error);
  2377. StyleableToast styleableToast = new StyleableToast
  2378. .Builder(getBaseContext())
  2379. .icon(R.drawable.ic_action_info)
  2380. .text("Network error, try again later")
  2381. .textColor(Color.WHITE)
  2382. .backgroundColor(Color.RED)
  2383. .build();
  2384. styleableToast.show();
  2385. }) {
  2386. protected Map<String, String> getParams() {
  2387. Map<String, String> MyData = new HashMap<>();
  2388. MyData.put("email", mEmail);
  2389. MyData.put("employee_name", mEmployeeName);
  2390. MyData.put("company_id", mCompanyID);
  2391. MyData.put("date_created_panic", tgl);
  2392. MyData.put("notes", note);
  2393. MyData.put("division", mDivision);
  2394. if(mPrefHelper.getLevelUser().equals("3")){
  2395. MyData.put("latitude", String.valueOf(logBookType.getSelectedItemPosition()+1));
  2396. MyData.put("type", "2");
  2397. }else{
  2398. MyData.put("type", "1");
  2399. }
  2400.  
  2401. return MyData;
  2402. }
  2403. };
  2404.  
  2405. // Adding request to request queue
  2406. NetworkRequest.getInstance(this).addToRequestQueue(jsonObjReq);
  2407.  
  2408. }
  2409.  
  2410. private void sendNotification(final String reg_token, String body, String title, String imgUrl) {
  2411. new AsyncTask<Void, Void, Void>() {
  2412. @Override
  2413. protected Void doInBackground(Void... params) {
  2414. try {
  2415. OkHttpClient client = new OkHttpClient();
  2416.  
  2417. SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
  2418. String times = timeformat.format(System.currentTimeMillis());
  2419.  
  2420. JSONObject root = new JSONObject();
  2421. JSONObject data = new JSONObject();
  2422. JSONObject payload = new JSONObject();
  2423.  
  2424. payload.put("title", title);
  2425. payload.put("is_background", false);
  2426. payload.put("message", body);
  2427. payload.put("image", imgUrl);
  2428. payload.put("timestamp", times);
  2429.  
  2430. data.put("data", payload);
  2431. root.put("data", data);
  2432. root.put("to", "/topics/" + reg_token);
  2433.  
  2434. RequestBody body = RequestBody.create(JSON, root.toString());
  2435. com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
  2436. .header("Authorization", "key=AIzaSyAwU7DMeeysvpQjcwZsS3hJFfx8wWcrpNU")
  2437. .url("https://fcm.googleapis.com/fcm/send")
  2438. .post(body)
  2439. .build();
  2440. Response response = client.newCall(request).execute();
  2441. String finalResponse = response.body().string();
  2442. Log.d(TAG, "doInBackground: " + finalResponse);
  2443.  
  2444.  
  2445. } catch (Exception e) {
  2446. //Log.d(TAG,e+"");
  2447. }
  2448. return null;
  2449. }
  2450. }.execute();
  2451.  
  2452. }
  2453.  
  2454. private void updateWidget() {
  2455. Intent intent = new Intent(this, TagInfo.class);
  2456. intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
  2457. int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TagInfo.class));
  2458. intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
  2459. sendBroadcast(intent);
  2460.  
  2461. }
  2462.  
  2463. private void absence(String logStatus, String distance) {
  2464.  
  2465.  
  2466.  
  2467. //String mCompanyID = sharedPref.getString("company_id", "olmatix1");
  2468. String mEmployeeName = sharedPref.getString("real_name", "olmatix1");
  2469. String mEmail = sharedPref.getString("email", "olmatix1");
  2470. //String mDivision = sharedPref.getString("division", "olmatix1");
  2471.  
  2472. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
  2473. String tgl = df.format(Calendar.getInstance().getTime());
  2474.  
  2475. String lat = String.valueOf(mPrefHelper.getPhoneLatitude());
  2476. String lot = String.valueOf(mPrefHelper.getPhoneLongitude());
  2477.  
  2478. String url_photo;
  2479. if(logStatus.equals("1")){
  2480. url_photo = mEmail + "-absence_in";
  2481. }else{
  2482. url_photo = mEmail + "-absence_out";
  2483. }
  2484.  
  2485.  
  2486. String url = Config.DOMAIN + "wamonitoring/insert_update_absense.php";
  2487.  
  2488. StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, response -> {
  2489. try {
  2490.  
  2491. JSONObject jObject = new JSONObject(response);
  2492. String result_code = jObject.getString("success");
  2493. String result_message = jObject.getString("message");
  2494.  
  2495. if (result_code.equals("1")) {
  2496.  
  2497. if (logStatus.equals("1")) {
  2498. //oNoFF.setText("Online");
  2499. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  2500.  
  2501. } else if (logStatus.equals("2")) {
  2502. //oNoFF.setText("Offline");
  2503. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  2504.  
  2505. }
  2506.  
  2507. mPrefHelper.setLogin(logStatus);
  2508. pDialog.dismiss();
  2509. //updateOn_Off(logStatus);
  2510.  
  2511. Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
  2512. pushNotification.putExtra("type", "8");
  2513. pushNotification.putExtra("message", "");
  2514. pushNotification.putExtra("user", "");
  2515. pushNotification.putExtra("timestamp", "");
  2516.  
  2517. LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
  2518. selfie = false;
  2519. } else {
  2520. firstopen = 0;
  2521. pDialog.dismiss();
  2522.  
  2523. if (result_message.equals("You have absence go work for today")) {
  2524. /* oNoFF.setChecked(false);
  2525. oNoFF.setText("Offline");*/
  2526. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  2527.  
  2528. }
  2529.  
  2530. if (result_message.equals("You have absence go home for today")){
  2531. /* oNoFF.setChecked(false);
  2532. oNoFF.setText("Offline");*/
  2533. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  2534.  
  2535. }
  2536.  
  2537. }
  2538.  
  2539. firstopen = 1;
  2540.  
  2541. styleableToast = new StyleableToast
  2542. .Builder(getBaseContext())
  2543. .icon(R.drawable.ic_action_info)
  2544. .text(String.valueOf(result_message))
  2545. .textColor(Color.WHITE)
  2546. .backgroundColor(Color.BLUE)
  2547. .build();
  2548. styleableToast.show();
  2549.  
  2550. //firstopen =1;
  2551.  
  2552. } catch (JSONException e) {
  2553. e.printStackTrace();
  2554. pDialog.dismiss();
  2555.  
  2556. }
  2557.  
  2558. }, error -> {
  2559. Log.d(TAG, "onErrorResponse: " + error);
  2560. if (mPrefHelper.getLogin().equals("1")){
  2561. oNoFF.setDirection(StickySwitch.Direction.RIGHT);
  2562.  
  2563. } else {
  2564. oNoFF.setDirection(StickySwitch.Direction.LEFT);
  2565.  
  2566. }
  2567.  
  2568. styleableToast = new StyleableToast
  2569. .Builder(getBaseContext())
  2570. .icon(R.drawable.ic_action_info)
  2571. .text(String.valueOf("Network error, try again later"))
  2572. .textColor(Color.WHITE)
  2573. .backgroundColor(Color.RED)
  2574. .build();
  2575. styleableToast.show();
  2576. pDialog.dismiss();
  2577.  
  2578. }
  2579.  
  2580. ) {
  2581. protected Map<String, String> getParams() {
  2582. Map<String, String> MyData = new HashMap<>();
  2583. MyData.put("email", mEmail);
  2584. MyData.put("employee_name", mEmployeeName);
  2585. MyData.put("latitude", lat);
  2586. MyData.put("longitude", lot);
  2587. MyData.put("log_status", logStatus);
  2588. MyData.put("date_created", tgl);
  2589. MyData.put("distance", distance);
  2590. MyData.put("foto", url_photo);
  2591. return MyData;
  2592. }
  2593. };
  2594.  
  2595. // Adding request to request queue
  2596. NetworkRequest.getInstance(this).addToRequestQueue(jsonObjReq);
  2597.  
  2598. }
  2599.  
  2600. /*@RequiresApi(api = Build.VERSION_CODES.N)
  2601. private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
  2602.  
  2603. return wanted.stream().filter(perm -> !hasPermission(perm)).collect(Collectors.toCollection(ArrayList::new));
  2604. }*/
  2605.  
  2606. private boolean hasPermission(String permission) {
  2607. if (canAskPermission()) {
  2608. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  2609. return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
  2610. }
  2611. }
  2612. return true;
  2613. }
  2614.  
  2615. private boolean canAskPermission() {
  2616. return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
  2617. }
  2618.  
  2619. public void showSettingsAlert() {
  2620. AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
  2621. alertDialog.setTitle("GPS is not Enabled!");
  2622. alertDialog.setMessage("Do you want to turn on GPS?");
  2623. alertDialog.setPositiveButton("Yes", (dialog, which) -> {
  2624. Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  2625. startActivity(intent);
  2626. });
  2627.  
  2628. alertDialog.setNegativeButton("No", (dialog, which) -> {
  2629. dialog.cancel();
  2630. //finish();
  2631. });
  2632.  
  2633. alertDialog.show();
  2634. }
  2635.  
  2636. /*@RequiresApi(api = Build.VERSION_CODES.N)
  2637. @Override
  2638. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  2639. switch (requestCode) {
  2640. case ALL_PERMISSIONS_RESULT:
  2641. Log.d(TAG, "onRequestPermissionsResult");
  2642. permissionsRejected.addAll(permissionsToRequest.stream().filter(perms -> !hasPermission(perms)).collect(Collectors.toList()));
  2643.  
  2644. if (permissionsRejected.size() > 0) {
  2645. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  2646. if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
  2647. showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
  2648. (dialog, which) -> {
  2649. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  2650. requestPermissions(permissionsRejected.toArray(
  2651. new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
  2652. }
  2653. });
  2654. return;
  2655. }
  2656. }
  2657. } else {
  2658. Log.d(TAG, "No rejected permissions.");
  2659. canGetLocation = true;
  2660. getLocation();
  2661. }
  2662. break;
  2663. }
  2664. }*/
  2665.  
  2666. private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
  2667. new AlertDialog.Builder(MainActivity.this)
  2668. .setMessage(message)
  2669. .setPositiveButton("OK", okListener)
  2670. .setNegativeButton("Cancel", null)
  2671. .create()
  2672. .show();
  2673. }
  2674.  
  2675.  
  2676. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement