Tag: gps

em kotlin: gps terceira versão com mapa

Adicionar uma dependência via menus no build-gradle (module)
(1)

ficheiro: build-gradle(module)

...
dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.android.gms:play-services-location:17.1.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

ficheiro: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pt.isec.estuda.amov_gpsv1">

    <!-- pedir estas permissões -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <!-- pedir estas permissões para aceder aos mapas e ao estado da rede não são em runtime -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Amov_gpsv1">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD4M076vcUKcPZNGlyBzFshU-J4jJ98x5g"/>
    </application>

</manifest>

ficheiro: MainActivity.kt

package pt.isec.estuda.amov_gpsv1

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.Color
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

const val TAG = "Location"

class MainActivity : AppCompatActivity(), OnMapReadyCallback{

    var locEnable = false //caso não ajam permissões

    lateinit var fLoc : FusedLocationProviderClient

    val ISEC = LatLng(40.1925, -8.4115)
    val DEIS = LatLng(40.1925, -8.4128)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fLoc = FusedLocationProviderClient(this)

        //pedir o objeto google maps e vai ser necessário o OnMapReadyCallback
        (supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment)?.getMapAsync(this)
    }

    override fun onResume() {
        super.onResume()
        startLocationServices(true)
        //para poupanças de energia, ativar o mais tarde possivel
    }

    override fun onPause() {
        super.onPause()
        //para poupanças de energia, desactivar o mais cedo possivel
        if(locEnable) {
            locEnable = false
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //se tivermos as permissões
        //locationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100f, this)
        if(requestCode == 1289) {
            startLocationServices(false)
        }
    }

    fun startLocationServices(askPerm : Boolean) {
        //1ºprovider, 2º intervalo de segundos,3º distancia minima ,4º  o listener
        //se for for telemovel NETWORK_PROVIDER
        //dar permissões: ACCESS_FINE_LOCATION
        //e pedir em runtime, add permissions check
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //pedir as permissões //&& ou ||
            if (askPerm) {
                ActivityCompat.requestPermissions(this, arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION), 1289) //1289 um valor qualquer!
            } else {
                finish()
            }
            return
        }
        val locRequest = LocationRequest().apply {
            interval = 4000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            //ocultar para ja estes dois:
            //fastestInterval = 2000
            //maxWaitTime = 10000
            //numUpdates /? a ver, quantidade de updates
        }
        //activar
        locEnable = true
        fLoc.requestLocationUpdates(locRequest, locationCallBack, null)
    }

    //função locationCallBack
    var locationCallBack = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            Log.i(TAG, "onLocationAvailability: ")
            //locations é uma lista de localizações
            p0?.locations?.forEach {
                Log.i(TAG, "onLocationAvailability: ${it.latitude} ${it.longitude}")
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun onMapReady(map: GoogleMap?) {
        //implementar o omMapReady, sendo p0 o ojecto google maps
        map ?: return //if map == null return
        map.isMyLocationEnabled = true
        map.uiSettings.isCompassEnabled = true
        map.uiSettings.isZoomControlsEnabled = true
        map.uiSettings.isZoomGesturesEnabled = true
        val cp = CameraPosition.Builder().target(ISEC).zoom(17f).bearing(0f).tilt(0f).build()
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cp))
        map.addCircle(
            CircleOptions().center(ISEC).radius(150.0).fillColor(Color.argb(128,128,128,128)).strokeColor(Color.rgb(128,0,0)).strokeWidth(4f)
        )
        val mo = MarkerOptions().position(ISEC).title("ISEC-IPC").snippet("Instituo.....")
        val isec = map.addMarker(mo)
        isec.showInfoWindow()
        map.addMarker(MarkerOptions().position(DEIS).title("DEIS-ISEC"))
    }

}

ficheiro: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- incluimos o mapa como um fragmento -->
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>
</FrameLayout>
Tags : , , , , , ,

em kotlin: gps segunda versão

Adicionar uma dependência via menus no build-gradle (module)
(1)

(2)

(3)

ficheiro: build-gradle(module)

...
dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.android.gms:play-services-location:17.1.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

ficheiro: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pt.isec.estuda.amov_gpsv1">

    <!-- pedir estas permissões -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Amov_gpsv1">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ficheiro: MainActivity.kt

package pt.isec.estuda.amov_gpsv1

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*

const val TAG = "Location"

class MainActivity : AppCompatActivity() {


    var locEnable = false //caso não ajam permissões

    lateinit var fLoc : FusedLocationProviderClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fLoc = FusedLocationProviderClient(this)
    }

    override fun onResume() {
        super.onResume()
        startLocationServices(true)
        //para poupanças de energia, ativar o mais tarde possivel
    }

    override fun onPause() {
        super.onPause()
        //para poupanças de energia, desactivar o mais cedo possivel
        if(locEnable) {
            locEnable = false
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //se tivermos as permissões
        //locationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100f, this)
        if(requestCode == 1289) {
            startLocationServices(false)
        }
    }

    fun startLocationServices(askPerm : Boolean) {
        //1ºprovider, 2º intervalo de segundos,3º distancia minima ,4º  o listener
        //se for for telemovel NETWORK_PROVIDER
        //dar permissões: ACCESS_FINE_LOCATION
        //e pedir em runtime, add permissions check
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //pedir as permissões //&& ou ||
            if (askPerm) {
                ActivityCompat.requestPermissions(this, arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION), 1289) //1289 um valor qualquer!
            } else {
                finish()
            }
            return
        }
        val locRequest = LocationRequest().apply {
            interval = 4000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            //ocultar para ja estes dois:
            //fastestInterval = 2000
            //maxWaitTime = 10000
            //numUpdates /? a ver, quantidade de updates
        }
        //activar
        locEnable = true
        fLoc.requestLocationUpdates(locRequest, locationCallBack, null)
    }


    }
    //função locationCallBack
    var locationCallBack = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            Log.i(TAG, "onLocationAvailability: ")
            //locations é uma lista de localizações
            p0?.locations?.forEach {
                Log.i(TAG, "onLocationAvailability: ${it.latitude} ${it.longitude}")
            }
        }
}

Com esta versão são feitos updates mais rapidamente, com a ajuda do LocationRequest.PRIORITY_HIGH_ACCURACY
este é o método recomendado pela google..

Tags : , , , , , ,

em kotlin: gps primeira versão

ficheiro: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pt.isec.estuda.amov_gpsv1">

    <!-- pedir estas permissões -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Amov_gpsv1">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ficheiro: MainActivity.kt

package pt.isec.estuda.amov_gpsv1

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat

const val TAG = "Location"

class MainActivity : AppCompatActivity(), LocationListener {

    lateinit var locationM : LocationManager
    var locEnable = false //caso não ajam permissões

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        locationM = getSystemService(LOCATION_SERVICE) as LocationManager
    }

    override fun onResume() {
        super.onResume()
        startLocationServices(true)
        //para poupanças de energia, ativar o mais tarde possivel
    }

    override fun onPause() {
        super.onPause()
        //para poupanças de energia, desactivar o mais cedo possivel
        if(locEnable) {
            locationM.removeUpdates(this)
            locEnable = false
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //se tivermos as permissões
        //locationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100f, this)
        if(requestCode == 1289) {
            startLocationServices(false)
        }
    }

    fun startLocationServices(askPerm : Boolean){
        //1ºprovider, 2º intervalo de segundos,3º distancia minima ,4º  o listener
        //se for for telemovel NETWORK_PROVIDER
        //dar permissões: ACCESS_FINE_LOCATION
        //e pedir em runtime, add permissions check
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //pedir as permissões //&& ou ||
                if(askPerm) {
                    ActivityCompat.requestPermissions(this, arrayOf(
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION), 1289) //1289 um valor qualquer!
                }else{
                    finish()
                }
            return
        }
        locationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100f, this)
        locEnable = true
        //outras:
        //addProximityAlert, funções de proximidade para um determinado local
        //addNmeaListener, ir buscar as mensagens de baixo nivel que um chip gps consegue obter
        //requestSingleUpdate, ir buscar apenas um update(uma localização armazenada)
        //getLastKnownLocation, obter um objeto Location, obtemos logo uma localização mesmo que não seja correta
        //providers, acerca dos requisitos da rede
    }

    override fun onLocationChanged(location: Location) {
        val latitude = location.latitude
        val longitude = location.longitude
        Log.i(TAG, "onLocationChanged: $latitude $longitude")
        //a ver o location.distanceTo()

    }
}
Tags : , , , , , ,