Once I launch the application , the background service can be started and stopped very well on click of button.
But, this only works fine until I am in the same instance of the app.
When I start the service and kills the application without stopping the service, and if I reopen the application afterwards, I am unable to stop the service on the button click from this instance.
This is my locationService
class
class LocationServiceforeground:Service() {
private val CHANNEL_ID = "foregroundService"
companion object{
fun startService(context: Context,message:String){
val startIntent = Intent(context,LocationServiceforeground::class.java)
startIntent.putExtra("inputextra",message)
ContextCompat.startForegroundService(context,startIntent)
}
fun stopService(context: Context){
val stopIntent = Intent(context,LocationServiceforeground::class.java)
context.stopService(stopIntent)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val input = intent?.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this,UserActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_NO_CREATE)
val notification = NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("foreground working")
.setContentText(input)
.setOngoing(true)
.setSmallIcon(R.drawable.locationtrack)
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.build()
startForeground(1,notification)
return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder? {
return null
}
private fun createNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val serviceChannel = NotificationChannel(CHANNEL_ID,"foreground service 1",NotificationManager.IMPORTANCE_DEFAULT)
val manager = getSystemService(NotificationManager::class.java)
manager!!.createNotificationChannel(serviceChannel)
}
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
this.stopSelf()
}
This is my UserActivity
:
class UserActivity : AppCompatActivity() {
lateinit var location: ImageView
lateinit var locationGif: ImageView
lateinit var beingTrack: TextView
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var locationRequest: LocationRequest
lateinit var locationCallback: LocationCallback
var isLocationSharing = false
lateinit var database: DatabaseReference
lateinit var sharePreference:SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user)
sharePreference = getSharedPreferences("sharePref", Context.MODE_PRIVATE)
val username = sharePreference.getString("username", "")
val logoutBtn = findViewById<Button>(R.id.logoutUser)
val statechange = findViewById<Button>(R.id.stateChange)
val statechange1 = findViewById<Button>(R.id.stateChange1)
val switchBtn = findViewById<SwitchCompat>(R.id.switchBtn)
locationGif = findViewById<ImageView>(R.id.locationGif)
Glide.with(this).load(R.drawable.locatiogif).into(locationGif)
beingTrack = findViewById<TextView>(R.id.beingTrack)
location = findViewById<ImageView>(R.id.location)
if (sharePreference.getString("isChecked", "") == "true") {
switchBtn.isChecked = true
shareLocation()
} else {
switchBtn.isChecked = false
isLocationSharing = false
LocationServiceforeground.stopService(this)
stopSharing()
}
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
locationRequest = LocationRequest.create().apply {
interval = 200
fastestInterval = 100
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult ?: return
database = FirebaseDatabase.getInstance().reference
if (isLocationSharing) {
for (location in locationResult.locations) {
val currentLat = location.latitude
val currentLong = location.longitude
database.child("$username").child("latitude").setValue(currentLat)
database.child("$username").child("longtitude").setValue(currentLong)
}
}
}
}
logoutBtn.setOnClickListener {
stopSharing()
startActivity(Intent(this, LoginActivity::class.java))
val editor = sharePreference.edit()
editor.putBoolean("isActive", false)
editor.putString("username", "")
editor.apply()
}
switchBtn.setOnClickListener {
val editor = sharePreference.edit()
if (switchBtn.isChecked) {
editor.putString("isChecked", "true")
shareLocation()
} else {
editor.putString("isChecked", "false")
stopSharing()
}
editor.apply()
}
}
private fun stopSharing() {
val stopIntent = Intent(this,LocationServiceforeground::class.java)
this.stopService(stopIntent)
isLocationSharing = false
LocationServiceforeground.stopService(this)
location.visibility = View.VISIBLE
beingTrack.visibility = View.INVISIBLE
locationGif.visibility = View.GONE
}
private fun shareLocation() {
isLocationSharing = true
LocationServiceforeground.startService(this, "service started")
location.visibility = View.GONE
beingTrack.visibility = View.VISIBLE
locationGif.visibility = View.VISIBLE
}
override fun onResume() {
super.onResume()
if (checkLocationPermission()) {
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
}
override fun onBackPressed() {
super.onBackPressed()
stopSharing()
startActivity(Intent(this, LoginActivity::class.java))
val editor = sharePreference.edit()
editor.putBoolean("isActive", false)
editor.putString("username", "")
editor.apply()
}
private fun checkLocationPermission(): Boolean {
var state = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
) {
state = true
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
),
101
)
}
} else state = true
return state
}
}