Location fetched as Ip address and send to server

This commit is contained in:
chandrashekhar reddy
2024-04-01 17:47:01 +05:30
parent e78ae3a29e
commit c91082ee6d
5 changed files with 318 additions and 329 deletions

View File

@@ -38,6 +38,7 @@ object DataHolder {
var hemoCubeTestData: HemoCubeTestData? = null var hemoCubeTestData: HemoCubeTestData? = null
var kitSerial: String = "" var kitSerial: String = ""
var location: UserData.Location? = null var location: UserData.Location? = null
var ipAddress: String = "0.0"
var testExp: Boolean = true var testExp: Boolean = true
var hemocubeResult: Double? = null var hemocubeResult: Double? = null
} }

View File

@@ -13,27 +13,12 @@
package com.example.hpostesting.presentation.dashboard package com.example.hpostesting.presentation.dashboard
import android.content.Context
import android.content.SharedPreferences
import android.os.BatteryManager
import android.os.Bundle import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.fragment.app.activityViewModels import androidx.fragment.app.Fragment
import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.constant.DataHolder
import com.example.hpostesting.data.model.patient.HemoCubeTestData
import com.example.hpostesting.presentation.adapter.OfflineUserListAdapter
import com.example.hpostesting.presentation.adapter.UserListAdapter
import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel
import com.example.hpostesting.presentation.testRight.TestRightViewModel
import `in`.sminnovations.hpostesting.R
import `in`.sminnovations.hpostesting.databinding.FragmentAboutBinding import `in`.sminnovations.hpostesting.databinding.FragmentAboutBinding
import `in`.sminnovations.hpostesting.databinding.FragmentActivitiesBinding
import `in`.sminnovations.hpostesting.databinding.FragmentHomeBinding
class AboutFragment : Fragment() { class AboutFragment : Fragment() {
private lateinit var binding: FragmentAboutBinding private lateinit var binding: FragmentAboutBinding

View File

@@ -14,25 +14,17 @@
package com.example.hpostesting.presentation.dashboard package com.example.hpostesting.presentation.dashboard
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import android.os.BatteryManager import android.os.BatteryManager
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.constant.DataHolder
import com.example.hpostesting.data.model.patient.HemoCubeTestData
import com.example.hpostesting.presentation.adapter.OfflineUserListAdapter import com.example.hpostesting.presentation.adapter.OfflineUserListAdapter
import com.example.hpostesting.presentation.adapter.UserListAdapter
import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel
import com.example.hpostesting.presentation.testRight.TestRightViewModel
import `in`.sminnovations.hpostesting.R
import `in`.sminnovations.hpostesting.databinding.FragmentActivitiesBinding import `in`.sminnovations.hpostesting.databinding.FragmentActivitiesBinding
import `in`.sminnovations.hpostesting.databinding.FragmentHomeBinding
class ActivitiesFragment : Fragment() { class ActivitiesFragment : Fragment() {
private lateinit var binding: FragmentActivitiesBinding private lateinit var binding: FragmentActivitiesBinding

View File

@@ -93,9 +93,8 @@ class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding private lateinit var binding: FragmentHomeBinding
private val viewModel: TestRightViewModel by activityViewModels() private val viewModel: TestRightViewModel by activityViewModels()
private val hemoCubeViewModel: HemoCubeViewModel by activityViewModels() private val hemoCubeViewModel: HemoCubeViewModel by activityViewModels()
private lateinit var rvAdapter: UserListAdapter // private lateinit var rvAdapter: UserListAdapter
private var batLevel: Int = private var batLevel: Int = 0 // Initialize with a default value, or obtain the actual battery level
0 // Initialize with a default value, or obtain the actual battery level
private lateinit var adapter: OfflineUserListAdapter private lateinit var adapter: OfflineUserListAdapter
private val homeViewModel: HemoCubeViewModel by activityViewModels() private val homeViewModel: HemoCubeViewModel by activityViewModels()
private var isTokenAvailable by Delegates.notNull<Boolean>() private var isTokenAvailable by Delegates.notNull<Boolean>()
@@ -249,8 +248,8 @@ class HomeFragment : Fragment() {
binding.internetAvailableCL.visibility = View.VISIBLE binding.internetAvailableCL.visibility = View.VISIBLE
binding.internetNotAvailableCL.visibility = View.GONE binding.internetNotAvailableCL.visibility = View.GONE
binding.pendingTest.visibility = View.VISIBLE binding.pendingTest.visibility = View.VISIBLE
loadUserData() // loadUserData()
setSearch() //setSearch()
checkForLocalDBData() checkForLocalDBData()
if (Constants.MOLBIO_INTEGRATION) { if (Constants.MOLBIO_INTEGRATION) {
checkForTokenAndUpdate() checkForTokenAndUpdate()
@@ -661,7 +660,7 @@ class HomeFragment : Fragment() {
val version = pInfo.versionName val version = pInfo.versionName
var labname = sharedPreference.getString(Constants.LABNAME,"") var labname = sharedPreference.getString(Constants.LABNAME,"")
return LoginRequest( return LoginRequest(
password = password, serialNumber = userID, username = userID, version = version, lab = labname password = password, serialNumber = userID, username = userID, version = version, lab = labname,location = DataHolder.location.toString()
) )
}//latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.location.toString() }//latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.location.toString()
@@ -814,46 +813,46 @@ class HomeFragment : Fragment() {
} }
private fun loadUserData() { // private fun loadUserData() {
try { // try {
val dateFormat = SimpleDateFormat("yyyy-MM-dd") // val dateFormat = SimpleDateFormat("yyyy-MM-dd")
val currentDate = Date() // val currentDate = Date()
val formattedDate = dateFormat.format(currentDate) // val formattedDate = dateFormat.format(currentDate)
val query = Firebase.firestore.collection("patientData") // val query = Firebase.firestore.collection("patientData")
.whereGreaterThanOrEqualTo("createdAt", formattedDate) // .whereGreaterThanOrEqualTo("createdAt", formattedDate)
.orderBy("createdAt", Query.Direction.DESCENDING) // .orderBy("createdAt", Query.Direction.DESCENDING)
// val query = Firebase.firestore.collection("patientData").whereEqualTo("testStatus", false) //// val query = Firebase.firestore.collection("patientData").whereEqualTo("testStatus", false)
query.get().addOnSuccessListener { // query.get().addOnSuccessListener {
if (it.documents.isEmpty()) { // if (it.documents.isEmpty()) {
binding.pendingTest.visibility = View.VISIBLE // binding.pendingTest.visibility = View.VISIBLE
} else { // } else {
binding.pendingTest.visibility = View.GONE // binding.pendingTest.visibility = View.GONE
} // }
} // }
val recyclerViewOptions = // val recyclerViewOptions =
FirestoreRecyclerOptions.Builder<UserData>().setQuery(query, UserData::class.java) // FirestoreRecyclerOptions.Builder<UserData>().setQuery(query, UserData::class.java)
.build() // .build()
//
val bm = requireContext().getSystemService(BATTERY_SERVICE) as BatteryManager // val bm = requireContext().getSystemService(BATTERY_SERVICE) as BatteryManager
val batLevel: Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) // val batLevel: Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
//
rvAdapter = view?.let { // rvAdapter = view?.let {
UserListAdapter( // UserListAdapter(
requireContext(), // requireContext(),
hemoCubeViewModel, // hemoCubeViewModel,
recyclerViewOptions, // recyclerViewOptions,
it, // it,
batLevel, // batLevel,
requireActivity() // requireActivity()
) // )
}!! // }!!
binding.rvOrder.adapter = rvAdapter // binding.rvOrder.adapter = rvAdapter
//
rvAdapter.startListening() // rvAdapter.startListening()
} catch (e: Exception) { // } catch (e: Exception) {
Firebase.crashlytics.recordException(e) // Firebase.crashlytics.recordException(e)
} // }
} // }
private fun saveUserId(userId: String) { private fun saveUserId(userId: String) {
with(sharedPreference.edit()) { with(sharedPreference.edit()) {
@@ -879,87 +878,87 @@ class HomeFragment : Fragment() {
dialog.show() dialog.show()
} }
private fun getData(search: String?, field: String) { // private fun getData(search: String?, field: String) {
val userSearchTrace = Firebase.performance.newTrace("user_search_trace") // val userSearchTrace = Firebase.performance.newTrace("user_search_trace")
userSearchTrace.start() // userSearchTrace.start()
//
// search?.replaceFirstChar {
// if (search.lowercase()
// .startsWith(it.lowercase())
// ) it.titlecase(Locale.getDefault()) else it.toString()
//
// }
// val currentDate = Date()
// val dateFormat = SimpleDateFormat("yyyyMMdd")
// val partition = dateFormat.format(currentDate)
// val searchTerm = partition + search
// val searchField = field + "Search"
// val query =
// Firebase.firestore.collection("patientData").orderBy(searchField).startAt(searchTerm)
// .endAt(searchTerm + "\uf8ff")
// query.get().addOnSuccessListener {
// userSearchTrace.stop()
// }
// val recyclerViewOptions =
// FirestoreRecyclerOptions.Builder<UserData>().setQuery(query, UserData::class.java)
// .build()
// val bm = requireContext().getSystemService(BATTERY_SERVICE) as BatteryManager
// batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
//
// rvAdapter = view?.let {
// UserListAdapter(
// requireContext(),
// hemoCubeViewModel,
// recyclerViewOptions,
// it,
// batLevel,
// requireActivity()
// )
// }!!
// binding.rvOrder.adapter = rvAdapter
// rvAdapter.startListening()
//
// userSearchTrace.stop()
// }
search?.replaceFirstChar { // private fun setSearch() {
if (search.lowercase() // binding.searchProduct.setOnQueryTextListener(object :
.startsWith(it.lowercase()) // androidx.appcompat.widget.SearchView.OnQueryTextListener {
) it.titlecase(Locale.getDefault()) else it.toString() // override fun onQueryTextSubmit(query: String?): Boolean {
// return if (!query.isNullOrEmpty()) {
} // val field = when {
val currentDate = Date() // binding.userIdRadioButton.isChecked -> "_id"
val dateFormat = SimpleDateFormat("yyyyMMdd") // binding.abhaIdRadioButton.isChecked -> "abhaId"
val partition = dateFormat.format(currentDate) // binding.aadharIdRadioButton.isChecked -> "aadharId"
val searchTerm = partition + search // else -> null
val searchField = field + "Search" // }
val query = //
Firebase.firestore.collection("patientData").orderBy(searchField).startAt(searchTerm) // field?.let { getData(query, it) }
.endAt(searchTerm + "\uf8ff") // false
query.get().addOnSuccessListener { //
userSearchTrace.stop() // } else {
} // // loadUserData()
val recyclerViewOptions = // false
FirestoreRecyclerOptions.Builder<UserData>().setQuery(query, UserData::class.java) // }
.build() // }
val bm = requireContext().getSystemService(BATTERY_SERVICE) as BatteryManager //
batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) // override fun onQueryTextChange(query: String?): Boolean {
// return if (!query.isNullOrEmpty()) {
rvAdapter = view?.let { // val field = when {
UserListAdapter( // binding.userIdRadioButton.isChecked -> "_id"
requireContext(), // binding.abhaIdRadioButton.isChecked -> "abhaId"
hemoCubeViewModel, // binding.aadharIdRadioButton.isChecked -> "aadharId"
recyclerViewOptions, // else -> null
it, // }
batLevel, // field?.let { getData(query, it) }
requireActivity() // false
) // } else {
}!! // // loadUserData()
binding.rvOrder.adapter = rvAdapter // false
rvAdapter.startListening() // }
// }
userSearchTrace.stop() // })
} // }
private fun setSearch() {
binding.searchProduct.setOnQueryTextListener(object :
androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return if (!query.isNullOrEmpty()) {
val field = when {
binding.userIdRadioButton.isChecked -> "_id"
binding.abhaIdRadioButton.isChecked -> "abhaId"
binding.aadharIdRadioButton.isChecked -> "aadharId"
else -> null
}
field?.let { getData(query, it) }
false
} else {
loadUserData()
false
}
}
override fun onQueryTextChange(query: String?): Boolean {
return if (!query.isNullOrEmpty()) {
val field = when {
binding.userIdRadioButton.isChecked -> "_id"
binding.abhaIdRadioButton.isChecked -> "abhaId"
binding.aadharIdRadioButton.isChecked -> "aadharId"
else -> null
}
field?.let { getData(query, it) }
false
} else {
loadUserData()
false
}
}
})
}
private fun checkForLocalDBData() { private fun checkForLocalDBData() {
// viewModel.allUserData.observe(viewLifecycleOwner) { userDataList -> // viewModel.allUserData.observe(viewLifecycleOwner) { userDataList ->

View File

@@ -13,16 +13,11 @@
package com.example.hpostesting.presentation.dashboard.ui package com.example.hpostesting.presentation.dashboard.ui
import android.Manifest
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.ConnectivityManager import android.net.ConnectivityManager
import android.net.NetworkInfo import android.net.NetworkCapabilities
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
@@ -31,27 +26,25 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Toast import android.widget.Toast
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.example.hpostesting.data.constant.Constants import com.example.hpostesting.data.constant.Constants
import com.google.android.gms.location.FusedLocationProviderClient import com.example.hpostesting.data.constant.DataHolder
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.R
import `in`.sminnovations.hpostesting.databinding.FragmentLoginBinding import `in`.sminnovations.hpostesting.databinding.FragmentLoginBinding
import java.net.NetworkInterface import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.net.HttpURLConnection
import java.net.URL
import java.util.Scanner
class LoginFragment : Fragment() { class LoginFragment : Fragment() {
private val LOCATION_PERMISSION_REQUEST_CODE = 1001 private val LOCATION_PERMISSION_REQUEST_CODE = 1001
private lateinit var locationManager: LocationManager // private lateinit var locationManager: LocationManager
var latitude = 0.0 // var latitude = 0.0
var longitude = 0.0 // var longitude = 0.0
var TAG = "LoginFragmentCheck" var TAG = "LoginFragmentCheck"
private var _binding: FragmentLoginBinding? = null private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!! private val binding get() = _binding!!
@@ -70,32 +63,41 @@ class LoginFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
init() init()
locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager if(isInternetAvailable()){
getPublicIpAddr { ipAddress ->
// Check for location permission DataHolder.ipAddress = ipAddress
if (ContextCompat.checkSelfPermission(requireContext(), }
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission is not granted, request it
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST_CODE)
} else {
// Permission is granted, fetch location
checkLocation()
} }
if (isNetworkProviderAvailable()) { // getPublicIpAddr { ipAddress ->
Toast.makeText(requireContext(), "Network provider is available", Toast.LENGTH_SHORT).show() // DataHolder.ipAddress = ipAddress
} else { // }
Toast.makeText(requireContext(), "Network provider is not available", Toast.LENGTH_SHORT).show() // locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
// // Check for location permission
// if (ContextCompat.checkSelfPermission(requireContext(),
// Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(requireContext(),
// Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// // Permission is not granted, request it
// ActivityCompat.requestPermissions(requireActivity(),
// arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION),
// LOCATION_PERMISSION_REQUEST_CODE)
// } else {
// // Permission is granted, fetch location
// checkLocation()
// }
//
// if (isNetworkProviderAvailable()) {
// Toast.makeText(requireContext(), "Network provider is available", Toast.LENGTH_SHORT).show()
// } else {
// Toast.makeText(requireContext(), "Network provider is not available", Toast.LENGTH_SHORT).show()
// }
} }
private fun isNetworkProviderAvailable(): Boolean { // private fun isNetworkProviderAvailable(): Boolean {
//
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) // return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} // }
private fun init() { private fun init() {
if (isUserLoggedIn()) { if (isUserLoggedIn()) {
navigateToHomeFragment() navigateToHomeFragment()
@@ -156,146 +158,156 @@ class LoginFragment : Fragment() {
} }
/** Check if we can get our location */ /** Check if we can get our location */
@SuppressLint("MissingPermission") // @SuppressLint("MissingPermission")
fun checkLocation() { // fun checkLocation() {
//
val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager // val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationProviderWifi = LocationManager.NETWORK_PROVIDER // val locationProviderWifi = LocationManager.NETWORK_PROVIDER
val locationProviderGPS = LocationManager.FUSED_PROVIDER // val locationProviderGPS = LocationManager.FUSED_PROVIDER
val locationListenerNetwork: LocationListener // val locationListenerNetwork: LocationListener
val locationListenerGPS: LocationListener // val locationListenerGPS: LocationListener
var gps_enabled = false // var gps_enabled = false
var network_enabled = false // var network_enabled = false
Log.d(TAG,"PRoveider"+locationManager.allProviders.toString()) // Log.d(TAG,"PRoveider"+locationManager.allProviders.toString())
//check wifi // //check wifi
//
//check wifi // //check wifi
val connectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager // val connectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) // val mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
//
if (mWifi!!.isConnected) { // if (mWifi!!.isConnected) {
Log.d(TAG, "Wifi connected") // Log.d(TAG, "Wifi connected")
} // }
//
//check gps and wifi availability // //check gps and wifi availability
//
//check gps and wifi availability // //check gps and wifi availability
try { // try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (ex: java.lang.Exception) { // } catch (ex: java.lang.Exception) {
} // }
//
try { // try {
network_enabled = // network_enabled =
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) // locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (ex: java.lang.Exception) { // } catch (ex: java.lang.Exception) {
} // }
//
if (!gps_enabled) { // if (!gps_enabled) {
Log.d(TAG, "GPS: Missing") // Log.d(TAG, "GPS: Missing")
} // }
if (!network_enabled) { // if (!network_enabled) {
Log.d(TAG, "Network: Missing") // Log.d(TAG, "Network: Missing")
} // }
//
/* Location change listeners */ // /* Location change listeners */
//
/* Location change listeners */try { // /* Location change listeners */try {
// Define a listener that responds to gps location updates // // Define a listener that responds to gps location updates
locationListenerGPS = object : LocationListener { // locationListenerGPS = object : LocationListener {
override fun onLocationChanged(location: Location) { // override fun onLocationChanged(location: Location) {
Log.d( // Log.d(
TAG, // TAG,
"GPS: Latitude: " + location.latitude + ", Longitude = " + location.longitude // "GPS: Latitude: " + location.latitude + ", Longitude = " + location.longitude
) // )
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.d(TAG, "GPS location found 1")
}
override fun onProviderEnabled(provider: String) {
Log.d(TAG, "GPS location found 2")
}
override fun onProviderDisabled(provider: String) {
Log.d(TAG, "GPS location found 3")
}
}
locationManager.requestLocationUpdates(
locationProviderGPS,
0,
0f,
locationListenerGPS
)
} catch (e: java.lang.Exception) {
Log.e(TAG, "Location Exception GPS: " + e.message)
}
try {
// Define a listener that responds to wifi location updates
locationListenerNetwork = object : LocationListener {
override fun onLocationChanged(location: Location) {
Log.d(
TAG,
"NW: Latitude: " + location.latitude + ", Longitude = " + location.longitude
)
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.d(TAG, "location found 1")
}
override fun onProviderEnabled(provider: String) {
Log.d(TAG, "location found 2")
}
override fun onProviderDisabled(provider: String) {
Log.d(TAG, "location found 3")
}
}
locationManager.requestLocationUpdates(
locationProviderWifi,
0,
0f,
locationListenerNetwork
)
} catch (e: java.lang.Exception) {
Log.e(TAG, "Location Exception: " + e.message)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, fetch location
checkLocation()
} else {
// Permission denied
Toast.makeText(requireContext(), "Location permission denied", Toast.LENGTH_SHORT).show()
}
}
}
// fun getPublicIpAddr(callback: (String) -> Unit) {
// GlobalScope.launch(Dispatchers.IO) {
// val url = URL("https://api.ipify.org")
// val conn = url.openConnection() as HttpURLConnection
// try {
// conn.connect()
// if (conn.responseCode == HttpURLConnection.HTTP_OK) {
// val scanner = Scanner(conn.inputStream)
// scanner.useDelimiter("\\A")
// if (scanner.hasNext()) {
// val ipAddress = scanner.next()
// callback(ipAddress)
// }
// } // }
// } finally { //
// conn.disconnect() // override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// Log.d(TAG, "GPS location found 1")
// }
//
// override fun onProviderEnabled(provider: String) {
// Log.d(TAG, "GPS location found 2")
// }
//
// override fun onProviderDisabled(provider: String) {
// Log.d(TAG, "GPS location found 3")
// }
// }
// locationManager.requestLocationUpdates(
// locationProviderGPS,
// 0,
// 0f,
// locationListenerGPS
// )
// } catch (e: java.lang.Exception) {
// Log.e(TAG, "Location Exception GPS: " + e.message)
// }
//
// try {
// // Define a listener that responds to wifi location updates
// locationListenerNetwork = object : LocationListener {
// override fun onLocationChanged(location: Location) {
// Log.d(
// TAG,
// "NW: Latitude: " + location.latitude + ", Longitude = " + location.longitude
// )
// }
//
// override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// Log.d(TAG, "location found 1")
// }
//
// override fun onProviderEnabled(provider: String) {
// Log.d(TAG, "location found 2")
// }
//
// override fun onProviderDisabled(provider: String) {
// Log.d(TAG, "location found 3")
// }
// }
// locationManager.requestLocationUpdates(
// locationProviderWifi,
// 0,
// 0f,
// locationListenerNetwork
// )
// } catch (e: java.lang.Exception) {
// Log.e(TAG, "Location Exception: " + e.message)
// }
//
// }
// override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
// if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// // Permission granted, fetch location
// checkLocation()
// } else {
// // Permission denied
// Toast.makeText(requireContext(), "Location permission denied", Toast.LENGTH_SHORT).show()
// } // }
// } // }
// } // }
private fun getPublicIpAddr(callback: (String) -> Unit) {
try {
GlobalScope.launch(Dispatchers.IO) {
val url = URL("https://api.ipify.org")
val conn = url.openConnection() as HttpURLConnection
try {
conn.connect()
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
val scanner = Scanner(conn.inputStream)
scanner.useDelimiter("\\A")
if (scanner.hasNext()) {
val ipAddress = scanner.next()
callback(ipAddress)
}
}
} finally {
conn.disconnect()
}
}
}catch (e: Exception){
Log.e(TAG,e.toString())
}
}
@SuppressLint("NewApi")
private fun isInternetAvailable(): Boolean {
val connectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
} }