From da195ab573dd13396e0639417d344a2e06865851 Mon Sep 17 00:00:00 2001 From: chandrashekhar reddy Date: Wed, 27 Mar 2024 15:10:06 +0530 Subject: [PATCH] Location fetch code added in login fragment without gps --- .../hpostesting/data/constant/Constants.kt | 2 +- .../hpostesting/presentation/MainActivity.kt | 16 +- .../presentation/dashboard/HomeFragment.kt | 247 ++++++++++-------- .../dashboard/ui/LoginFragment.kt | 92 +++++++ app/src/main/res/layout/fragment_home.xml | 2 +- 5 files changed, 234 insertions(+), 125 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt index 28a9327..77c969d 100644 --- a/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt +++ b/app/src/main/java/com/example/hpostesting/data/constant/Constants.kt @@ -259,7 +259,7 @@ object Constants { const val BUFFER_VALUE_3 = "BufferValue3" const val BUFFER_VALUE_4 = "BufferValue4" const val DEVICE_ID = "DEVICE_ID" - + const val IS_TOKEN_AVAILABLE = "IS_TOKEN_AVAILABLE" const val BUFFER_LED_LOWER_BOUND = 21000 const val BUFFER_LED_UPPER_BOUND = 23500 diff --git a/app/src/main/java/com/example/hpostesting/presentation/MainActivity.kt b/app/src/main/java/com/example/hpostesting/presentation/MainActivity.kt index 3da3f0e..215c942 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/MainActivity.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/MainActivity.kt @@ -84,10 +84,10 @@ class MainActivity : AppCompatActivity() { locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { locationResult.lastLocation?.let { location -> - DataHolder.location = - UserData.Location(location.latitude, location.longitude) - DataHolder.selectedTest?.location = - UserData.Location(location.latitude, location.longitude) +// DataHolder.location = +// UserData.Location(location.latitude, location.longitude) +// DataHolder.selectedTest?.location = +// UserData.Location(location.latitude, location.longitude) Log.i("Location", DataHolder.location.toString()) } } @@ -314,14 +314,14 @@ class MainActivity : AppCompatActivity() { fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? -> location?.let { if (DataHolder.selectedTest != null) { - DataHolder.selectedTest!!.location = - UserData.Location(location.latitude, location.longitude) +// DataHolder.selectedTest!!.location = +// UserData.Location(location.latitude, location.longitude) } else { startActivity(Intent(this, DashboardActivity::class.java)) finish() } - DataHolder.location = - UserData.Location(location.latitude, location.longitude) +// DataHolder.location = +// UserData.Location(location.latitude, location.longitude) } ?: run { requestLocationUpdates() } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index 32372bf..918345f 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -13,16 +13,7 @@ package com.example.hpostesting.presentation.dashboard -// Copyright (c) 2024 ShanMukha Innovations Pvt. Ltd. All rights reserved. -// Notice: All information contained herein is, and remains -// the property of ShanMukha Innovations Pvt. Ltd. and its suppliers, -// if any. The intellectual and technical concepts contained -// herein are proprietary to ShanMukha Innovations Pvt. Ltd. -// and its suppliers and may be covered by Indian and Foreign Patents, -// patents in process, and are protected by trade secret or copyright law. -// Dissemination of this information or reproduction of this material -// is strictly forbidden unless prior written permission is obtained -// from ShanMukha Innovations Pvt. Ltd. +import android.Manifest import android.annotation.SuppressLint import android.app.AlertDialog import android.app.DownloadManager @@ -34,6 +25,10 @@ import android.content.DialogInterface import android.content.Intent import android.content.IntentFilter import android.content.SharedPreferences +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager import android.net.Uri import android.os.BatteryManager import android.os.Build @@ -47,6 +42,7 @@ import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi +import androidx.core.app.ActivityCompat import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels @@ -96,9 +92,11 @@ import java.util.Date import java.util.Locale import java.util.zip.ZipEntry import java.util.zip.ZipInputStream +import kotlin.properties.Delegates @AndroidEntryPoint class HomeFragment : Fragment() { + private var wasConnected = false private var isRegistered = false private var downloadId: Long = 0 private lateinit var binding: FragmentHomeBinding @@ -109,8 +107,7 @@ class HomeFragment : Fragment() { 0 // Initialize with a default value, or obtain the actual battery level private lateinit var adapter: OfflineUserListAdapter private val homeViewModel: HemoCubeViewModel by activityViewModels() - - private var isTokenAvailable = false + private var isTokenAvailable by Delegates.notNull() private var natsToken: String = "" private var deviceId: String = "" private lateinit var sharedPreference: SharedPreferences @@ -122,6 +119,7 @@ class HomeFragment : Fragment() { sharedPreference = requireContext().getSharedPreferences("HEMOCUBE", Context.MODE_PRIVATE) DataHolder.selectedTest = null + isTokenAvailable = sharedPreference.getBoolean(Constants.IS_TOKEN_AVAILABLE, false) return binding.root } @@ -166,92 +164,8 @@ class HomeFragment : Fragment() { // } // // } - viewModel.networkStatusLiveData?.observe(viewLifecycleOwner) { isConnected -> - if (isConnected) { - binding.internetAvailableCL.visibility = View.VISIBLE - binding.internetNotAvailableCL.visibility = View.GONE - binding.pendingTest.visibility = View.VISIBLE - loadUserData() - setSearch() - checkForLocalDBData() - if (Constants.MOLBIO_INTEGRATION) { - checkForTokenAndUpdate() - } - // Now re-subscribe to allUserData - /* hemoCubeViewModel.allLocalData.observe(viewLifecycleOwner) { originalUserDataList -> - Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED") - - val resultList = MolbioV2ResultRequest(mutableListOf()) - originalUserDataList.forEach { userData -> - Log.d( - ": USER DATA", - originalUserDataList.count().toString() + " : " + userData._id - ) - var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() - // Upload results after processing all userData to avoid duplicates and ensure all modifications are done - if(accessToken.isNotEmpty()) { - if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { - val currentTimeFormatted = SimpleDateFormat( - "yyyy-MM-dd'T'HH:mm:ssZZZZZ", - Locale.getDefault() - ).format(Calendar.getInstance().time) - val bufferIntensityThreshold = - Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() - ?: "defaultThreshold" // Handle possible nulls safely - resultList.results?.add( - MolbioV2Result( - rawData = userData, - analysisId = userData._id, - analysisDate = currentTimeFormatted, - analysisStatus = userData.classificationResult - ?: "defaultStatus", // Handle possible nulls - thresholds = bufferIntensityThreshold, - interpretation = userData.classificationResult - ?: "defaultInterpretation", // Handle possible nulls - testId = userData._id, - testTime = currentTimeFormatted, - collectionTime = currentTimeFormatted, - expiryTime = currentTimeFormatted - ) - ) - } - } - } - Log.d("USER DATA LIST SIZE", resultList.results?.count().toString()) - - resultList.results?.forEach { result -> - val userData = result.rawData - Log.d("UserData", userData.toString()) - if (userData != null) { - if (!userData.localFlag) { - hemoCubeViewModel.bulkAddResultTestToDb(userData) - - } - } - } - resultList.results?.forEach { result -> - result.rawData?.let { sanitizeDoubleValues(it) } - } - - // Then, check if there are any results to upload. - if (resultList.results?.isNotEmpty() == true) { - hemoCubeViewModel.uploadResult(resultList) - Log.d("resultcount1", "Uploading sanitized results") - } - - }*/ - hemoCubeViewModel.sendDataToMolbio() - hemoCubeViewModel.sendDataToFirebase() - - } else { - binding.internetAvailableCL.visibility = View.GONE - binding.pendingTest.visibility = View.GONE - binding.internetNotAvailableCL.visibility = View.VISIBLE - setUserId() - } - } hemoCubeViewModel.fireBaseBulkUpload.observe(viewLifecycleOwner) { result -> if (result == "Success") { Toast.makeText( @@ -330,9 +244,104 @@ class HomeFragment : Fragment() { binding.downloadCSV.setOnClickListener { showDownloadDialog(requireContext()) } + //calling network change listener + checkNetworkStatus() } + @RequiresApi(Build.VERSION_CODES.P) + private fun checkNetworkStatus() { + hemoCubeViewModel.networkStatusLiveData.observe(viewLifecycleOwner) { isConnected -> + if (isConnected != wasConnected) { + if (isConnected) { + binding.internetAvailableCL.visibility = View.VISIBLE + binding.internetNotAvailableCL.visibility = View.GONE + binding.pendingTest.visibility = View.VISIBLE + loadUserData() + setSearch() + checkForLocalDBData() + if (Constants.MOLBIO_INTEGRATION) { + checkForTokenAndUpdate() + } + + // Now re-subscribe to allUserData + /* hemoCubeViewModel.allLocalData.observe(viewLifecycleOwner) { originalUserDataList -> + + Log.d("LOCAL_DB OBSERVE", "OBSERVE CALLED") + + val resultList = MolbioV2ResultRequest(mutableListOf()) + originalUserDataList.forEach { userData -> + Log.d( + ": USER DATA", + originalUserDataList.count().toString() + " : " + userData._id + ) + var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() + // Upload results after processing all userData to avoid duplicates and ensure all modifications are done + if(accessToken.isNotEmpty()) { + if (!userData.molbioFlag && isTokenAvailable && Constants.MOLBIO_INTEGRATION) { + val currentTimeFormatted = SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + Locale.getDefault() + ).format(Calendar.getInstance().time) + val bufferIntensityThreshold = + Constants.BUFFER_INTENSITY_THRESHOLDS[userData.deviceId]?.toString() + ?: "defaultThreshold" // Handle possible nulls safely + resultList.results?.add( + MolbioV2Result( + rawData = userData, + analysisId = userData._id, + analysisDate = currentTimeFormatted, + analysisStatus = userData.classificationResult + ?: "defaultStatus", // Handle possible nulls + thresholds = bufferIntensityThreshold, + interpretation = userData.classificationResult + ?: "defaultInterpretation", // Handle possible nulls + testId = userData._id, + testTime = currentTimeFormatted, + collectionTime = currentTimeFormatted, + expiryTime = currentTimeFormatted + ) + ) + } + } + } + Log.d("USER DATA LIST SIZE", resultList.results?.count().toString()) + + resultList.results?.forEach { result -> + val userData = result.rawData + Log.d("UserData", userData.toString()) + if (userData != null) { + if (!userData.localFlag) { + hemoCubeViewModel.bulkAddResultTestToDb(userData) + + } + } + } + resultList.results?.forEach { result -> + result.rawData?.let { sanitizeDoubleValues(it) } + } + + // Then, check if there are any results to upload. + if (resultList.results?.isNotEmpty() == true) { + hemoCubeViewModel.uploadResult(resultList) + Log.d("resultcount1", "Uploading sanitized results") + } + + }*/ + hemoCubeViewModel.sendDataToMolbio() + hemoCubeViewModel.sendDataToFirebase() + + } else { + binding.internetAvailableCL.visibility = View.GONE + binding.pendingTest.visibility = View.GONE + binding.internetNotAvailableCL.visibility = View.VISIBLE + setUserId() + } + wasConnected = isConnected + } + } + } + @RequiresApi(Build.VERSION_CODES.P) private fun checkForTokenAndUpdate() { var accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString() @@ -348,18 +357,20 @@ class HomeFragment : Fragment() { if (!isTokenAvailable) { Log.d("istoken1", isTokenAvailable.toString()) hemoCubeViewModel.login(createLoginRequestData(userID, password)) - isTokenAvailable = true + + //isTokenAvailable = true } else if (isTokenAvailable) { Log.d("istoken7", isTokenAvailable.toString()) - isTokenAvailable = true - hemoCubeViewModel.startPeriodicCheckUpdate() - hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) - } else { if (isTokenExpired(accessToken)) { Log.d("istoken8", isTokenAvailable.toString()) hemoCubeViewModel.login(createLoginRequestData(userID, password)) + //hemoCubeViewModel.startPeriodicCheckUpdate() + }else{ + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) } + //isTokenAvailable = true + // hemoCubeViewModel.startPeriodicCheckUpdate() } } else if (userID == "deviceIDAPI" && password == "devicePasswordAPI" && deviceId.isNotEmpty()) { fetchDeviceCredentials() @@ -374,18 +385,15 @@ class HomeFragment : Fragment() { Toast.makeText(context, "DECRYPTED: $credentials", Toast.LENGTH_SHORT).show() if (!isTokenAvailable) { hemoCubeViewModel.login(createLoginRequestData(userID, password)) - isTokenAvailable = true - } -// else if (isTokenAvailable) { -// isTokenAvailable = true -// hemoCubeViewModel.startPeriodicCheckUpdate() -// hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) -// } else { -// if (isTokenExpired(accessToken)) { -// hemoCubeViewModel.login(createLoginRequestData(userID, password)) -// } -// } + else if (isTokenAvailable) { + //hemoCubeViewModel.startPeriodicCheckUpdate() + if (isTokenExpired(accessToken)) { + hemoCubeViewModel.login(createLoginRequestData(userID, password)) + }else{ + hemoCubeViewModel.checkUpdate(createCheckUpdateRequestData()) + } + } } else { Toast.makeText( requireContext(), @@ -399,7 +407,10 @@ class HomeFragment : Fragment() { is Result.Success -> { updateTokens(response) response.data.data?.accessToken - isTokenAvailable = true + with(sharedPreference.edit()) { + putBoolean(Constants.IS_TOKEN_AVAILABLE, true) + apply() + } Log.d("istoken2", isTokenAvailable.toString()) } @@ -622,7 +633,10 @@ class HomeFragment : Fragment() { ) apply() } - isTokenAvailable = true + with(sharedPreference.edit()) { + putBoolean(Constants.IS_TOKEN_AVAILABLE, true) + apply() + } Log.d("istoken3", isTokenAvailable.toString()) } @@ -632,7 +646,7 @@ class HomeFragment : Fragment() { ) val version = pInfo.versionName return LoginRequest( - password = password, serialNumber = userID, username = userID, version = version + password = password, serialNumber = userID, username = userID, version = version, latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.location.toString() ) } @@ -1151,6 +1165,8 @@ class HomeFragment : Fragment() { override fun onDestroyView() { super.onDestroyView() + hemoCubeViewModel.networkStatusLiveData.removeObservers(viewLifecycleOwner) + } private fun downloadCsv() { @@ -1458,4 +1474,5 @@ class HomeFragment : Fragment() { } + } diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt index b2591c9..39081b3 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt @@ -13,20 +13,36 @@ package com.example.hpostesting.presentation.dashboard.ui +import android.Manifest +import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager +import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast +import androidx.annotation.RequiresApi +import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.hpostesting.data.constant.Constants +import com.example.hpostesting.data.constant.DataHolder +import com.example.hpostesting.data.model.patient.UserData import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.FragmentLoginBinding +import kotlin.properties.Delegates class LoginFragment : Fragment() { + private lateinit var locationManager: LocationManager + var latitude by Delegates.notNull() + var longitude by Delegates.notNull() + private var locationListener: LocationListener? = null private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! @@ -43,7 +59,40 @@ class LoginFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + locationManager = + requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager + locationListener = MyLocationListener() init() + // Check for permissions + if (ActivityCompat.checkSelfPermission( + requireContext(), + Manifest.permission.ACCESS_FINE_LOCATION + ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( + requireContext(), + Manifest.permission.ACCESS_COARSE_LOCATION + ) != PackageManager.PERMISSION_GRANTED + ) { + // Request permissions if not granted + ActivityCompat.requestPermissions( + requireActivity(), + arrayOf( + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION + ), + 123 + ) + return + } + + // Request location updates using NETWORK_PROVIDER + locationManager.requestLocationUpdates( + LocationManager.NETWORK_PROVIDER, + 0, + 0f, + locationListener as LocationListener + ) + + } private fun init() { @@ -101,5 +150,48 @@ class LoginFragment : Fragment() { override fun onDestroyView() { super.onDestroyView() _binding = null + locationManager.removeUpdates(locationListener as LocationListener) + } + @SuppressLint("MissingPermission") + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == 123) { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // Permission granted, request location updates again + locationManager.requestLocationUpdates( + LocationManager.NETWORK_PROVIDER, + 0, + 0f, + locationListener as LocationListener + ) + } + } + } + + inner class MyLocationListener : LocationListener { + @RequiresApi(Build.VERSION_CODES.P) + override fun onLocationChanged(location: Location) { + // Handle location change here + latitude = location.latitude + longitude = location.longitude + + DataHolder.location = + UserData.Location(location.latitude, location.longitude) + DataHolder.selectedTest?.location = + UserData.Location(location.latitude, location.longitude) + // Toast.makeText(requireContext(), "location$latitude/$longitude",Toast.LENGTH_SHORT).show() + + // Do something with latitude and longitude + } + + override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {} + + override fun onProviderEnabled(provider: String) {} + + override fun onProviderDisabled(provider: String) {} } } diff --git a/app/src/main/res/layout/fragment_home.xml b/app/src/main/res/layout/fragment_home.xml index 83c68df..ec26bd5 100644 --- a/app/src/main/res/layout/fragment_home.xml +++ b/app/src/main/res/layout/fragment_home.xml @@ -193,7 +193,7 @@ android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/upload_data" - android:visibility="visible" + android:visibility="gone" app:layout_constraintBottom_toBottomOf="@+id/tv_title" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/tv_title" />