Uploaded by sarwaqoali2022

Coursework Application detailed

advertisement
→ Goal : create an App, which detects the longitude and the latitude of your position and
save them in sharedPreferences.
→ here, we have our first page(Avtivity_main.xml)
→ I designed for 4 TextViews and 2 Buttons.
→ 2 textview are for longitude and latitude and 2 others are for displaying the values on the
screen.
→ the 2 buttons : one is for getting the location and the another one is for retriving the last
longitude and latitude saved in the SharedPreferences.
Activity-main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity"
tools:ignore="MissingDefaultResource">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:padding="10dp"
android:text="Latitude : " />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/latitudetextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text=" " />
</LinearLayout>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:padding="10dp"
android:text="Longitude : " />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/longitudetextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text=" " />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_marginTop="200dp"
android:text="Saved"/>
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="200dp"
android:layout_weight="1"
android:text="Get Location" />
</LinearLayout>
</LinearLayout>
→ and here’s our Main_activity.kt, so in this activity I linked the 2 buttons with Event
Listener. When we click the first one, which is get location we call getCurrentLocation
function, which check the permissions, if location is enabled and detects the longitude and
the latitude. If everything works correctly it displays in the textView. And it automatically
saves in the sharePreferences.
→ it tells, permission is denied, if the user didn’t give a permission.
→ and if something went wrong it displays 0.0 for the longitude and the latitude.
→ the second button is for retriving the last longitude and the latitude , which we saved.
Main-activity.kt
package com.example.locationapp
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.Manifest
android.content.Context
android.content.Intent
android.content.SharedPreferences
android.content.pm.PackageManager
android.location.Location
android.location.LocationManager
android.media.audiofx.Equalizer.Settings
androidx.appcompat.app.AppCompatActivity
android.os.Bundle
android.widget.Button
android.widget.TextView
android.widget.Toast
androidx.core.app.ActivityCompat
com.google.android.gms.location.FusedLocationProviderClient
com.google.android.gms.location.LocationServices
class MainActivity : AppCompatActivity() {
private lateinit var fusedLocationProviderClient:
FusedLocationProviderClient
private lateinit var textview1:TextView
private lateinit var textView2: TextView
private lateinit var button:Button
private lateinit var button2:Button
private lateinit var button3:Button
private lateinit var latitudeview:TextView
private lateinit var longitudeview:TextView
private lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fusedLocationProviderClient=LocationServices.getFusedLocationProviderClient
(this)
textview1=findViewById(R.id.textView)
textView2=findViewById(R.id.textView2)
button=findViewById(R.id.button1)
button2=findViewById(R.id.button2)
button3=findViewById(R.id.button2)
latitudeview=findViewById(R.id.latitudetextView)
longitudeview=findViewById(R.id.longitudetextView)
sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
button.setOnClickListener {
getCurrentLocation();
}
button2.setOnClickListener {
getFromShared()
}
}
private fun getFromShared() {
val savedLatitude=sharedPreferences.getFloat("latitude",
0.0F).toDouble()
val savedLongtitude=sharedPreferences.getFloat("longitude",
0.0F).toDouble()
latitudeview.text= ""+savedLatitude.toString()
longitudeview.text=""+savedLongtitude.toString()
}
private fun getCurrentLocation() {
if(checkPermissions()){
if(isLocationEnabled())
{
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermission()
return
}
fusedLocationProviderClient.lastLocation.addOnCompleteListener(this){ task>
val location: Location?=task.result
if(location==null){
Toast.makeText(this,"Null
received",Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this,"Get
Success",Toast.LENGTH_SHORT).show()
latitudeview.text= ""+location.latitude
longitudeview.text=""+location.longitude
val editor = sharedPreferences.edit()
editor.putFloat("longitude",location.longitude.toFloat())
editor.putFloat("latitude",location.latitude.toFloat())
editor.apply()
}
}
}
else{
Toast.makeText(this,"Turn location
on",Toast.LENGTH_SHORT).show()
val
intent=Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}else{
requestPermission()
}
}
private fun isLocationEnabled():Boolean{
val
locationManager:LocationManager=getSystemService(Context.LOCATION_SERVICE)
as LocationManager
return
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
private fun requestPermission() {
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_LOCATION)
}
companion object{
private const val PERMISSION_REQUEST_ACCESS_LOCATION=100
}
private fun checkPermissions():Boolean{
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCE
SS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_
FINE_LOCATION)==PackageManager.PERMISSION_GRANTED ){
return true
}
return false
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults)
if(requestCode== PERMISSION_REQUEST_ACCESS_LOCATION){
if(grantResults.isNotEmpty() &&
grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(applicationContext,"Access Granted",
Toast.LENGTH_SHORT).show()
getCurrentLocation()
}
else{
Toast.makeText(applicationContext,"Permission
Denied",Toast.LENGTH_SHORT).show()
}
}
}
}
→ and in our androidManifest I wrote all the permissions required in order to get
the longitude and the latitude. Permission like Access_BACKGROUND (gor
cheking the location in background ) and Access_fine location.
android manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission
android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.LocationApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
→ This implementation statement adds the Google Play services location library
with version 19.0.1 to an Android project. It enables access to location-based
services and functionalities in Android applications.
Build-gradle.kts
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.example.locationapp"
compileSdk = 34
defaultConfig {
applicationId = "com.example.locationapp"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner =
"androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation ("com.google.android.gms:play-services-location:19.0.1")
}
→ Application :
→ if the App didn’t save data it returns 0.0
→ Conclusion :
→the App asks for permission and then detect the latitude and the longitude.
→ If the location is turn off , it ask to turn the location on.
→ if the permission is denied it says, permission denied.
→ if the user clicked the saved button it displays the latest longitude and latitude.
Related documents
Download