I want to display the coordinates on the phone screen dynamically as the user moves the phone. I want this to happen as soon as the app is turned on, without the user having to press any buttons. I guess the closest to an XYZ coordinates would be the lat/long? But I don’t know how to loop it so that it immediately starts in OnCreate() and will last as long as the app is on.
Here’s what I have right now in MainActivity.java, which I think is probably wrong:
package com.example.musicapp1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
LocationManager lm;
Location location;
double longitude, latitude;
TextView coor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(this.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
coor.setText("longitude: " + longitude + ", latitude: " + latitude);
}
}
When I try it on my phone, the textview coor
just says the default text textview
and doesn’t show the lat/long at all. I already have these permissions in my AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
Is there a way to do this? It doesn’t have to be lat/long, I’m prioritizing the phone’s XY coordinates only. (I’m very new to Android Studio.)
Thank you.