Weather gps now works properly with nicer code as well

This commit is contained in:
ottoptj 2024-08-08 18:10:18 +03:00
commit bcb8f331b3
10 changed files with 78 additions and 61 deletions

View file

@ -17,6 +17,7 @@ import android.widget.EditText
import android.widget.Toast import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.setFragmentResult import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference import androidx.preference.Preference
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@ -43,7 +44,7 @@ class GestureAppsFragment : Fragment(), GestureAppsAdapter.OnItemClickListener {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
CoroutineScope(Dispatchers.Main).launch { lifecycleScope.launch {
withContext(Dispatchers.Default) { withContext(Dispatchers.Default) {

View file

@ -12,6 +12,7 @@ import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import android.widget.EditText import android.widget.EditText
import androidx.fragment.app.setFragmentResult import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference import androidx.preference.Preference
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -44,7 +45,7 @@ class LocationFragment : Fragment(), LocationListAdapter.OnItemClickListener {
stringUtils.setLink(requireActivity().findViewById(R.id.locationLink), getString(R.string.location_link)) stringUtils.setLink(requireActivity().findViewById(R.id.locationLink), getString(R.string.location_link))
CoroutineScope(Dispatchers.IO).launch { lifecycleScope.launch(Dispatchers.IO) {
locationList = weatherSystem.getSearchedLocations( locationList = weatherSystem.getSearchedLocations(
searchView.text.toString() searchView.text.toString()
) )
@ -75,7 +76,7 @@ class LocationFragment : Fragment(), LocationListAdapter.OnItemClickListener {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
println(searchView.text.toString()) println(searchView.text.toString())
CoroutineScope(Dispatchers.IO).launch { lifecycleScope.launch(Dispatchers.IO){
val locations = weatherSystem.getSearchedLocations( val locations = weatherSystem.getSearchedLocations(
searchView.text.toString() searchView.text.toString()
) )

View file

@ -44,6 +44,10 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.ResourcesCompat
import androidx.core.view.children import androidx.core.view.children
import androidx.core.view.marginLeft import androidx.core.view.marginLeft
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
@ -189,6 +193,28 @@ class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceCh
} }
}) })
lifecycleScope.launch(Dispatchers.IO) {
repeatOnLifecycle(Lifecycle.State.STARTED) {
while (true) {
updateWeather()
delay(600000)
}
}
}
}
private suspend fun updateWeather() {
withContext(Dispatchers.IO) {
if (preferences.getBoolean("weather_enabled", false)) {
if (preferences.getBoolean("gps_location", false)) {
weatherSystem.setGpsLocation(this@MainActivity)
} else {
updateWeatherText()
}
}
}
} }
fun modifyDate(value: String, index: Int) { fun modifyDate(value: String, index: Int) {
@ -197,22 +223,12 @@ class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceCh
dateText.format24Hour = "${dateElements[1]}${stringUtils.addStartTextIfNotEmpty(dateElements[2], " | ")}${stringUtils.addStartTextIfNotEmpty(dateElements[3], " | ")}" dateText.format24Hour = "${dateElements[1]}${stringUtils.addStartTextIfNotEmpty(dateElements[2], " | ")}${stringUtils.addStartTextIfNotEmpty(dateElements[3], " | ")}"
} }
private fun startWeatherMonitor() {
weatherJob?.cancel()
weatherJob = CoroutineScope(Dispatchers.IO).launch {
while (true) {
if (preferences.getBoolean("gps_location", false)) {
withContext(Dispatchers.Main) {
weatherSystem.setGpsLocation(this@MainActivity)
}
}
val currentWeather = weatherSystem.getTemp(this@MainActivity)
suspend fun updateWeatherText() {
val temp = weatherSystem.getTemp(this@MainActivity)
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
modifyDate(currentWeather, 2) modifyDate(temp, 2)
}
delay(300000)
}
} }
} }
@ -261,7 +277,9 @@ class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceCh
"weather_enabled" -> { "weather_enabled" -> {
if (preferences?.getBoolean(key, false) == true) { if (preferences?.getBoolean(key, false) == true) {
startWeatherMonitor() lifecycleScope.launch {
updateWeather()
}
} }
else { else {
weatherJob?.cancel() weatherJob?.cancel()
@ -363,9 +381,6 @@ class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceCh
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
startTask() startTask()
if (preferences.getBoolean("weather_enabled", false)) {
startWeatherMonitor()
}
// Keyboard is sometimes open when going back to the app, so close it. // Keyboard is sometimes open when going back to the app, so close it.
closeKeyboard() closeKeyboard()

View file

@ -36,9 +36,6 @@ class SettingsFragment : PreferenceFragmentCompat() {
gpsLocationPref.onPreferenceChangeListener = gpsLocationPref.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue -> Preference.OnPreferenceChangeListener { _, newValue ->
val isGpsEnabled = newValue as Boolean val isGpsEnabled = newValue as Boolean
if (isGpsEnabled) {
weatherSystem.setGpsLocation(requireActivity())
}
manualLocationPref?.isEnabled = !isGpsEnabled manualLocationPref?.isEnabled = !isGpsEnabled
true // Returning true means the change is persisted true // Returning true means the change is persisted
} }

View file

@ -7,32 +7,32 @@ import android.content.pm.PackageManager
import android.location.Location import android.location.Location
import android.location.LocationListener import android.location.LocationListener
import android.location.LocationManager import android.location.LocationManager
import android.os.Handler
import android.os.Looper
import android.widget.Toast import android.widget.Toast
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
import kotlin.coroutines.coroutineContext
class WeatherSystem { class WeatherSystem {
private val sharedPreferenceManager = SharedPreferenceManager() private val sharedPreferenceManager = SharedPreferenceManager()
private val stringUtils = StringUtils() private val stringUtils = StringUtils()
fun setGpsLocation(activity: Activity) { suspend fun setGpsLocation(activity: MainActivity) {
val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
println("Location obtained")
locationManager.removeUpdates(this)
}
}
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions( ActivityCompat.requestPermissions(
activity, activity,
@ -42,17 +42,20 @@ class WeatherSystem {
return return
} }
locationManager.getCurrentLocation(
locationManager.requestLocationUpdates(LocationManager.FUSED_PROVIDER, 0, 0f, locationListener) LocationManager.GPS_PROVIDER, // Use GPS provider
null, // No cancellation signal
ContextCompat.getMainExecutor(activity)
val currentLocation = locationManager.getLastKnownLocation(LocationManager.FUSED_PROVIDER) )
{ location: Location? -> // Lambda expression for the callback
if (location != null) {
if (currentLocation != null) { CoroutineScope(Dispatchers.IO).launch {
sharedPreferenceManager.setWeatherLocation(activity, "latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}", sharedPreferenceManager.getWeatherRegion(activity)) val latitude = location.latitude
val longitude = location.longitude
sharedPreferenceManager.setWeatherLocation(activity, "latitude=${latitude}&longitude=${longitude}", sharedPreferenceManager.getWeatherRegion(activity))
activity.updateWeatherText()}
}
} }
} }

View file

@ -127,13 +127,13 @@
<Space <Space
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.25" /> android:layout_weight="0.23" />
<TextView <TextView
android:id="@+id/app1" android:id="@+id/app1"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -150,7 +150,7 @@
android:id="@+id/app2" android:id="@+id/app2"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -168,7 +168,7 @@
android:id="@+id/app3" android:id="@+id/app3"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -186,7 +186,7 @@
android:id="@+id/app4" android:id="@+id/app4"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -204,7 +204,7 @@
android:id="@+id/app5" android:id="@+id/app5"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -222,7 +222,7 @@
android:id="@+id/app6" android:id="@+id/app6"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -240,7 +240,7 @@
android:id="@+id/app7" android:id="@+id/app7"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"
@ -258,7 +258,7 @@
android:id="@+id/app8" android:id="@+id/app8"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="0.08" android:layout_weight="0.09"
android:autoSizeMaxTextSize="28sp" android:autoSizeMaxTextSize="28sp"
android:autoSizeTextType="uniform" android:autoSizeTextType="uniform"
android:clickable="false" android:clickable="false"

View file

@ -117,8 +117,8 @@
android:text="Stripe" android:text="Stripe"
android:textAlignment="center" android:textAlignment="center"
android:textSize="20sp" android:textSize="20sp"
app:layout_constraintEnd_toStartOf="@+id/githubLink" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintStart_toEndOf="@+id/liberaLink"
app:layout_constraintTop_toBottomOf="@+id/divider2" /> app:layout_constraintTop_toBottomOf="@+id/divider2" />
<TextView <TextView
@ -130,8 +130,8 @@
android:text="Liberapay" android:text="Liberapay"
android:textAlignment="center" android:textAlignment="center"
android:textSize="20sp" android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toStartOf="@+id/stripeLink"
app:layout_constraintStart_toEndOf="@+id/codebergLink" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider2" /> app:layout_constraintTop_toBottomOf="@+id/divider2" />
<TextView <TextView

View file

@ -70,8 +70,8 @@
<string name="codeberg_link"><![CDATA[<a href="https://codeberg.org/ottoptj/yamlauncher">Codeberg</a>]]></string> <string name="codeberg_link"><![CDATA[<a href="https://codeberg.org/ottoptj/yamlauncher">Codeberg</a>]]></string>
<string name="github_link"><![CDATA[<a href="https://github.com">GitHub</a>]]></string> <string name="github_link"><![CDATA[<a href="https://github.com">GitHub</a>]]></string>
<string name="stripe_link"><![CDATA[<a href="https://codeberg.org/ottoptj/yamlauncher">Stripe</a>]]></string> <string name="libera_link"><![CDATA[<a href="https://github.com">Liberapay</a><br>(recurring)]]></string>
<string name="libera_link"><![CDATA[<a href="https://github.com">Liberapay</a>]]></string> <string name="stripe_link"><![CDATA[<a href="https://codeberg.org/ottoptj/yamlauncher">Stripe</a><br>(one-time)]]></string>
<string name="weather_link"><![CDATA[Weather data by <a href="https://open-meteo.com/">Open-Meteo.com</a><br>(<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>)]]></string> <string name="weather_link"><![CDATA[Weather data by <a href="https://open-meteo.com/">Open-Meteo.com</a><br>(<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>)]]></string>
<string name="location_link"><![CDATA[Location data by <a href="https://open-meteo.com/">Open-Meteo.com</a> (<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>)]]></string> <string name="location_link"><![CDATA[Location data by <a href="https://open-meteo.com/">Open-Meteo.com</a> (<a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>)]]></string>

View file

@ -7,7 +7,7 @@
<item name="android:navigationBarColor">@android:color/transparent</item> <item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:statusBarColor">@android:color/transparent</item> <item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">?attr/isLightTheme</item> <item name="android:windowLightStatusBar">?attr/isLightTheme</item>
<item name="android:windowFullscreen">false</item> <item name="android:windowFullscreen">true</item>
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item> <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<item name="android:enforceNavigationBarContrast">false</item> <item name="android:enforceNavigationBarContrast">false</item>
<item name="android:enforceStatusBarContrast">false</item> <item name="android:enforceStatusBarContrast">false</item>

View file

@ -109,7 +109,7 @@
app:entries="@array/size_options" app:entries="@array/size_options"
app:entryValues="@array/size_values" app:entryValues="@array/size_values"
app:key="shortcutSize" app:key="shortcutSize"
app:title="Home App Size" app:title="Shortcut Size"
app:useSimpleSummaryProvider="true" /> app:useSimpleSummaryProvider="true" />
<ListPreference <ListPreference
android:layout_width="wrap_content" android:layout_width="wrap_content"