Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

<application
android:allowBackup="true"
Expand Down
57 changes: 39 additions & 18 deletions app/src/main/java/me/tangobee/weathernaut/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package me.tangobee.weathernaut

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.cancel
import me.tangobee.weathernaut.data.RetrofitHelper
Expand All @@ -27,38 +31,47 @@ import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

private lateinit var weatherViewModel: WeatherViewModel
private lateinit var coroutineExceptionHandler: CoroutineExceptionHandler
private lateinit var sharedPreferencesHelper: SharedPreferencesHelper

private var settingsUpdated = false

// For requesting notification permissions
private val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
Toast.makeText(this, "Notification permission granted", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Notification permission denied", Toast.LENGTH_SHORT).show()
}
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val splashScreen = installSplashScreen()
binding = ActivityMainBinding.inflate(layoutInflater)

sharedPreferencesHelper = SharedPreferencesHelper(this)

val noInternetLiveData : MutableLiveData<Boolean> = MutableLiveData(false)
val noInternetLiveData : MutableLiveData<Boolean> = MutableLiveData(false)

coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable ->
if(throwable is UnknownHostException) {
// Handle internet-related errors
coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
if (throwable is UnknownHostException) {
noInternetLiveData.postValue(true)
}
}

noInternetLiveData.observe(this) {noInternet ->
if(noInternet) {
Toast.makeText(this, getString(R.string.no_internet), Toast.LENGTH_LONG).show()
Thread.sleep(1000)
exitProcess(0)
}


// Request notification permission for Android 13+ (API 33+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotificationPermission()
}

val settingsModel = SharedPreferencesHelper(this).getSettings()
if(settingsModel?.isMusicOn != false) {
if (settingsModel?.isMusicOn != false) {
val startMusicIntent = Intent(this, WeatherMusicService::class.java)
startService(startMusicIntent)
}
Expand All @@ -69,28 +82,35 @@ class MainActivity : AppCompatActivity() {
setContentView(binding.root)
}

private fun requestNotificationPermission() {
if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// Request notification permission
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}

private fun fetchData() {
val weatherService = RetrofitHelper.getInstance().create(WeatherService::class.java)
val weatherRepository = WeatherRepository(weatherService)
weatherViewModel = ViewModelProvider(this, WeatherViewModelFactory(weatherRepository))[WeatherViewModel::class.java]

val geocodingData = sharedPreferencesHelper.getGeocodingData()

if(weatherViewModel.weatherLiveData.value == null) {
if(geocodingData == null) {
if (weatherViewModel.weatherLiveData.value == null) {
if (geocodingData == null) {
weatherViewModel.getWeather(coroutineExceptionHandler)
} else {
weatherViewModel.getGeoWeather(coroutineExceptionHandler, geocodingData)
}
}

weatherViewModel.weatherLiveData.observe(this) { weatherData ->
if(weatherData == null) {
if (weatherData == null) {
Toast.makeText(this, getString(R.string.api_fetching_error), Toast.LENGTH_SHORT).show()
Thread.sleep(1000)
exitProcess(0)
} else {
if(!settingsUpdated) {
if (!settingsUpdated) {
createLocalDB(weatherData)
}
}
Expand All @@ -103,7 +123,7 @@ class MainActivity : AppCompatActivity() {
val weatherHelper = WeatherHelper(currentSettings, weatherData)
val newWeatherData = weatherHelper.convertWeatherData()

if(newWeatherData != weatherData) {
if (newWeatherData != weatherData) {
settingsUpdated = true
weatherViewModel.updateWeatherData(newWeatherData)
}
Expand All @@ -112,6 +132,7 @@ class MainActivity : AppCompatActivity() {

override fun onDestroy() {
super.onDestroy()
weatherViewModel.weatherLiveData.removeObservers(this)
weatherViewModel.viewModelScope.cancel("ActivityDestroying")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package me.tangobee.weathernaut.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
import android.content.pm.ServiceInfo
import android.media.MediaPlayer
import android.os.IBinder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import me.tangobee.weathernaut.R

Expand All @@ -20,68 +21,84 @@ class WeatherMusicService : Service() {

private val musicUrl = "https://weathernaut-backend.onrender.com/api/music"
private val SERVICE_ID = 1
private val CHANNEL_ID = "MUSIC_SERVICE_CHANNEL"

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createNotificationChannel()

// Foreground notification
val notification: Notification = NotificationCompat.Builder(this, "MUSIC_SERVICE_CHANNEL")
// Check if the service was called with the "STOP_MUSIC" action to stop the music
if (intent?.action == "STOP_MUSIC") {
stopSelf() // Stop the service and the music
return START_NOT_STICKY
}

// Intent for stopping the music through notification action
val stopMusicIntent = Intent(this, WeatherMusicService::class.java).apply {
action = "STOP_MUSIC"
}
val stopMusicPendingIntent = PendingIntent.getService(
this, 0, stopMusicIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

// Foreground notification with action to stop music
val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Playing Weather Music")
.setContentText("Enjoy the music and your day's weather!")
.setSmallIcon(R.drawable.icon_music)
.setSmallIcon(R.drawable.icon_music) // Replace with your own icon
.addAction(R.drawable.baseline_stop_24, "Stop Music", stopMusicPendingIntent) // Action to stop music
.build()

// Start the service in the foreground with the notification
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
startForeground(SERVICE_ID, notification)
} else {
startForeground(SERVICE_ID, notification,
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
startForeground(SERVICE_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
}

// Initialize or restart the media player
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer().apply {
setDataSource(musicUrl)
prepareAsync()
prepareAsync() // Async preparation for streaming
setOnPreparedListener {
it.start()
it.start() // Start playing music when ready
}
setOnCompletionListener {
start()
start() // Loop the music when it ends
}
setOnErrorListener { _, _, _ ->
stopSelf()
stopSelf() // Stop service on error
false
}
}
} else if (!mediaPlayer!!.isPlaying) {
mediaPlayer!!.start()
mediaPlayer!!.start() // Resume music if it's paused
}

return START_STICKY
}

override fun onDestroy() {
super.onDestroy()
if (mediaPlayer != null) {
mediaPlayer?.stop()
mediaPlayer?.release()
mediaPlayer = null
}
}

override fun onBind(intent: Intent?): IBinder? {
return null // We don't bind this service to an activity
}

// Create notification channel for Android 8.0 and above
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
"MUSIC_SERVICE_CHANNEL",
CHANNEL_ID,
"Music Playback Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(serviceChannel)
}
}

override fun onDestroy() {
super.onDestroy()
mediaPlayer?.stop()
mediaPlayer?.release()
mediaPlayer = null
}

override fun onBind(intent: Intent?): IBinder? {
return null // We don't bind this service to an activity
}
}
5 changes: 5 additions & 0 deletions app/src/main/res/drawable/baseline_stop_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="24dp" android:tint="#000000" android:viewportHeight="24" android:viewportWidth="24" android:width="24dp">

<path android:fillColor="@android:color/white" android:pathData="M6,6h12v12H6z"/>

</vector>
2 changes: 1 addition & 1 deletion app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<resources>
<string name="app_name">Weathernaut</string>

<string name="retry">Retry</string>
<string name="api_fetching_error">Something went wrong!\nDon\'t worry its not you, its us. Try later.</string>
<string name="no_internet">No Internet Connection</string>
<string name="search_cities_button">Search Cities Button</string>
Expand Down