Advertisement

Responsive Advertisement

Current Location with Services

 package com.example.roshan

import android.Manifest
import android.app.Activity
import android.app.Service
import android.content.Intent
import android.content.IntentSender.SendIntentException
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.IBinder
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import java.util.*

class MyServices : Service() {
var locationManager: LocationManager? = null
var locationListener: LocationListener? = null
var latitude: Double? = null
var longitude: Double? = null
var address: Double? = null
var smf: SupportMapFragment? = null


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

onLocation()
locationAdd()

//
// Toast.makeText(
// applicationContext, "This is a Service running in Background",
// Toast.LENGTH_SHORT
// ).show()
return START_STICKY
}
override fun onBind(intent: Intent): IBinder? {
// TODO: Return the communication channel to the service.
throw UnsupportedOperationException("Not yet implemented")
}
override fun onTaskRemoved(rootIntent: Intent) {
val restartServiceIntent = Intent(applicationContext, this.javaClass)
restartServiceIntent.setPackage(packageName)
startService(restartServiceIntent)
super.onTaskRemoved(rootIntent)
}
private fun onLocation() {
val googleApiClient = GoogleApiClient.Builder(applicationContext)
.addApi(LocationServices.API).build()
googleApiClient.connect()
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 10000
locationRequest.fastestInterval = (10000 / 2).toLong()
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
builder.setAlwaysShow(true)
val result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
result.setResultCallback { result ->
val status = result.status
when (status.statusCode) {
LocationSettingsStatusCodes.SUCCESS -> //Log.i(TAG, "All location settings are satisfied.");
try {
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
val lastKnownLocation =
locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
latitude = lastKnownLocation!!.latitude
longitude = lastKnownLocation.longitude
// strlatitude = latitude.toString()
// strlongitude = longitude.toString()
// stoplang = lastKnownLocation.longitude.toString()
// stoplatt = lastKnownLocation.latitude.toString()
Toast.makeText(
applicationContext,
"ok "+latitude+" "+longitude,Toast.LENGTH_SHORT
).show()
// straddress= lastKnownLocation.toString();
// Toast.makeText(Odometer.this, ""+strlatitude+","+strlongitude+",", Toast.LENGTH_LONG).show();
}
} catch (e: Exception) {
e.printStackTrace()
}
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> //Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(
applicationContext as Activity,
MapLocationActivity.REQUEST_CHECK_SETTINGS
)
} catch (e: SendIntentException) {
//Log.i(TAG, "PendingIntent unable to execute request.");
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {}
}
}
}

private fun locationAdd() {
// Progressbar.show("Please Wait....",this);
locationManager = this.getSystemService(LOCATION_SERVICE) as LocationManager
locationListener = LocationListener { location: Location ->
val geocoder = Geocoder(applicationContext, Locale.getDefault())
try {
val listAddress =
geocoder.getFromLocation(
latitude!!, longitude!!, 1
)
if (listAddress != null && listAddress.size > 0) {
/* address = listAddress.get(0).getAddressLine(0);*/
// noteslocation=listAddress.get(0).getAddressLine(0);
// Toast.makeText(Odometer.this, "data is "+noteslocation, Toast.LENGTH_SHORT).show();
// Log.d("noteslocation","noteslocation"+noteslocation);
//retaileraddress.setText(listAddress.get(0).getAddressLine(0));
smf!!.getMapAsync { googleMap ->
val latLng =
LatLng(
location.latitude,
location.longitude
)
val markerOptions = MarkerOptions().position(latLng)
.title(listAddress[0].getAddressLine(0))
googleMap.addMarker(markerOptions)
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f))
// Toast.makeText(getApplicationContext(), "ok "+latitude + longitude, Toast.LENGTH_SHORT).show();
}
}
} catch (e: Exception) {
// Progressbar.dismiss();
e.printStackTrace()
}
}
// Toast.makeText(Odometer.this, "data is "+noteslocation, Toast.LENGTH_SHORT).show();
if (ContextCompat.checkSelfPermission( this ,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
applicationContext as Activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
1
)
} else {
onLocation()
// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, (float) 0, (android.location.LocationListener) locationListener);
}
}
}

Post a Comment

0 Comments