I want to know the distance between two coordinates.
When the coordinates change, I want to know the distance between them in a meter.
Code MainActivity:
private TextView textView;
private TextView label3,label2;
private EditText editText;
protected LocationManager locationManager;
private String name;
double latitude;
double longitude;
RequestQueue queue;
double Lan;
double Lon;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
label3 = (TextView)findViewById(R.id.label3);
label2 = (TextView)findViewById(R.id.label2);
textView = (TextView) findViewById(R.id.label);
int permissionStatus = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionStatus == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(),"access is",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 10,
10, this);
queue = Volley.newRequestQueue(this);
}
#Override
public void onLocationChanged(final Location location) {
textView.setText("My location = Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
if (latitude != location.getLatitude() && longitude != location.getLongitude()) {
Toast.makeText(this,"location changed",Toast.LENGTH_LONG).show();
latitude = location.getLatitude();
longitude = location.getLongitude();
getvalue();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.e("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("Latitude","status");
}
public void Insert(View view){
name = editText.getText().toString();
Insert.BackGround b=new Insert.BackGround();
String lan = String.valueOf(latitude);
String lon = String.valueOf(longitude);
b.execute(name,lan,lon);
String result = b.Result();
Toast.makeText(this,result,Toast.LENGTH_LONG).show();
}
public void getvalue(){
Log.e("st","getvalue");
String url = "http://my_url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
Lan = response.getDouble("latitude");
Lon = response.getDouble("longitude");
Log.e("lan", String.valueOf(Lan));
Log.e("lon", String.valueOf(Lon));
calculate(latitude,longitude,Lan,Lon);
label3.setText("name="+name+" Lan="+Lan+" Lon="+Lon);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(request);
}
public void calculate( double lan1, double lon1, double lan2, double lon2){
Log.e("st","calculate");
Location loc1 = new Location("point A");
loc1.setLatitude(lan1);
loc1.setLongitude(lon1);
Location loc2 = new Location("point B");
loc2.setLatitude(lan2);
loc2.setLongitude(lon2);
String distanceInMeters = String.valueOf(loc1.distanceTo(loc2));
label2.setText("Distance = "+distanceInMeters );
}
Manifest:
<uses-sdk
android:targetSdkVersion="28" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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/AppTheme"
android:networkSecurityConfig="#xml/network_security_config"
android:usesCleartextTraffic="true"
android:testOnly="false"
android:debuggable="true"
tools:ignore="HardcodedDebugMode">
The program works well in
Redmi Note 4 and emulator BlueStacks
but in Redmi Note 5 and Android > 8 app give such error "app keeps stopping"
I can not find the error and answer on the Internet
help me please
I would be very happy if someone writes a code which works in any device :)
Android logcat
2020-02-26 18:22:42.553 3897-3897/com.example.getlocation E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
2020-02-26 18:22:42.554 3897-3897/com.example.getlocation E/GMPM: Scheduler not set. Not logging error/warn.
2020-02-26 18:22:42.560 3897-3927/com.example.getlocation E/GMPM: Uploading is not possible. App measurement disabled
2020-02-26 18:22:44.854 3897-3897/com.example.getlocation E/st: getvalue
2020-02-26 18:22:44.874 3897-3931/com.example.getlocation E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.getlocation, PID: 3897
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:108)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/app/com.example.getlocation-9UATZ0srGfq2w1rY4vtYKQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.getlocation-9UATZ0srGfq2w1rY4vtYKQ==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:108)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
You are probably using a deprecated library for volley. Use official version instead
implementation 'com.android.volley:volley:1.1.1'
For other issue I see in log cat is related to this GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have developed an app that sends the user's location via SMS. When I starting building it there were no errors, but when it is being tested with an actual phone it crashes ... It would not open.
public class MainActivity extends AppCompatActivity {
EditText phone;
Button emergency;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone= (EditText) findViewById(R.id.number);
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GPStracker g = new GPStracker(getApplicationContext());
Location l = g.getLocation();
if (l != null) {
double lat = l.getLatitude();
double lon = l.getLongitude();
String message = "http://maps.google.com/maps?saddr=" + lat + "," + lon;
String number = "number";
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append(Uri.parse(message));
android.telephony.SmsManager.getDefault().sendTextMessage(number, null, smsBody.toString(), null, null);
}
}
});
}
AND ALSO HERE IS MY CLASS FOR GPS TRACKING
public class GPStracker implements LocationListener {
Context context;
public GPStracker(Context c){
context = c;
}
public Location getLocation(){
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,this);
Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return l;
}else{
Toast.makeText(context,"Please enable GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
}
}
AND MY MANIFEST FILE
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.research.sos.smshelpcaller">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I ALREADY TRY EVERYTHING BUT I DON'T KNOW WHAT IS WRONG IN MY CODES OR IS THERE SOMETHING MISSING.
LASTLY HERE IS THE LOGS IN LOGCAT
04-03 13:55:56.472 31224-31224/com.research.sos.smshelpcaller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.research.sos.smshelpcaller, PID: 31224
java.lang.NullPointerException: Attempt to get length of null array
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1493)
at com.android.internal.telephony.ISms$Stub$Proxy.sendText(ISms.java:1430)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:320)
at com.research.sos.smshelpcaller.MainActivity$1.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:5052)
at android.view.View$PerformClick.run(View.java:20162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
where is your layout file,
Give your xml reference to activity after super.onCreate(savedInstanceState);.
for example..
setContentView(R.layout.activity_main);
According to your log you try to invoke method on Null Pointer:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.research.sos.smshelpcaller.MainActivity.onCreate(MainActivity.java:23)
It means, that the code below does not resolve the R.id.emergency asset. It simply can't find it and the first line is set to null:
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {...}
You should check if the name of the button you try to use is correct, if there is no spell mistakes, or even if the resource file (for example xml with view) exists.
Actually I'm building an application which requires user's location. But I'm getting SERVICE_VERSION_UPDATE_REQUIRED error. Following are my MainActivity.java and AndroidManifest.xml files:
MainActivity.java
TextView lat, lon;
private static final String TAG = MainActivity.class.getSimpleName();
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat = (TextView) findViewById(R.id.lat);
lon = (TextView) findViewById(R.id.lon);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText("Latitude: " + String.valueOf(latitude));
lon.setText("Longitude: " + String.valueOf(longitude));
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.harshil.location">
<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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is what logcat says:
D/MainActivity: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
So, How to get through this problem?
I solved my problem by changing following line [in build.gradle] from:
compile 'com.google.android.gms:play-services:10.0.1'
to:
compile 'com.google.android.gms:play-services:9.8.0'
So, the problem is I am using higher version of Google Play Service for development than that installed on my device or emulator.
I came to my solution as follow:
1. I checked to update Google Play Service on my device but it says it is up-to-date.
2. I checked in App Manager to see the version of it, and I came to know that it is actually at 9.8.77. So I changed play-service version from 10.0.1 to 9.8.0.
Now, I am out of this problem.
Thank you.
Download the the google play store in your mobile and check it .for me i was not installed google play store in my mobile now i installed google play store ,its working fine.
I'm new at android development and really confused by this problem.
I'm making a simple app which has 3 TextViews: text, text2 and text3.
text shows the latitude of user
text2 shows the longitude of the user and
text3 shows distance between user and the place called "Azadi Square".
The app runs properly on Samsung Galaxy S4 and Samsung Galaxy Tab S, but in Huawei Y511 and one of Sony Xperias (I do not know the exact name.), the app doesn't Open and says The App has unfortunately stopped
Here is my Java code:
public class Map extends Activity implements LocationListener {
private TextView text,text2,text3;
private String provider;
private LocationManager locationManager;
private double latitude,longitude;
private Location azadiSquare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
text = (TextView)findViewById(R.id.text);
text2 = (TextView)findViewById(R.id.text2);
text3 = (TextView)findViewById(R.id.text3);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
azadiSquare = new Location(provider);
azadiSquare.setLatitude(35.6996540);
azadiSquare.setLongitude(51.3379906);
Location location = locationManager.getLastKnownLocation(provider);
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude()+"");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,400,1,this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
text.setText(latitude+"");
text2.setText(longitude+"");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this,"Enabled new provider " + provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this,"Disabled provider " + provider,Toast.LENGTH_LONG).show();
}
private double getDistanceFromLatLonInKm(double lat1,double lon1,double lat2,double lon2) {
double R = 6371; // Radius of the earth in km
double dLat = deg2rad(lat2-lat1); // deg2rad below
double dLon = deg2rad(lon2-lon1);
double a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c; // Distance in km
return d;
}
private double deg2rad(double deg) {
return deg * (Math.PI/180);
}
private int distanceBetweenMeter(Location location1, Location location2){
double distanceKM = getDistanceFromLatLonInKm(location1.getLatitude(),location1.getLongitude(),
location2.getLatitude(),location2.getLongitude());
int distanceMeter = (int)(distanceKM*1000);
return distanceMeter;
}
}
Note: I just deleted the imports!
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/>
<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:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Map" android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Notes: I turned On the Location of the phone before opening the app, so it is not the problem. The other thing I want to say is that all the calculations are okay and they are working fine.
On Android 6.0 (API level 23) and higher you need to request permission for ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION at run time. See, Requesting Permissions at Run Time. That may be the case.
The best thing to do is to logcat the issue and backtrace it so you could see where it's going bad or at least have one clue. If the answer from user35603 didn't worked then try this and post the logcat part regarding to your issue.
Finally the problem is solved! This part of the code was making trouble:
Location location = locationManager.getLastKnownLocation(provider);
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude()+"");
I guess it takes a little bit of time for location to get the current location. Actually, when app wants to run the line below, location is still null and app crashes:
text1.setText(location.getLatitude()+"");
I solved the crash with something like this:
Location location = locationManager.getLastKnownLocation(provider);
while(location==null){}
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude() + "");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
Crash is solved, but the app freezes with white screen. I don't know exactly, but I guess it is trapped on while loop. Thanks!
public class MainActivity extends AppCompatActivity {
pb=findViewById(R.id.progressbar);
Example ex=new Example();//The subclass object is created here
boolean stop=false;//a boolean variable to start or stop the thread to get location.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (location== null) {
showSettingDialog();//this will show your custom way of displaying
//the location setting intent
new Thread(ex).start();//here the fetching location gets started
}
else{
//here write code after your location is fetched
//here to got some other base activity or stay in this
finish();//if you wan to stay in this activity then omit this line.
}
}
public class Example implements Runnable{ //This is a sub class in your main activity.
#Override
public void run() {//overriding run medthod
try {
while(location==null) { //this part keeps on running whithout
//ui freeze
if (stop) {
return;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
pb.setVisibility(View.VISIBLE);
}
});
getLastLocation();//this function will fetch location.
Thread.sleep(1500);
pb.setVisibility(View.INVISIBLE);
if (location != null) {
//do your code here
stop = true;
finish();
}
}
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
This question already has answers here:
How do I get the current GPS location programmatically in Android?
(21 answers)
Closed 9 years ago.
I'm having troubles of getting my current position coordinates using the NETWORK provider of android location system.
Already read a lot of tutorials and implemented 4 or 5 existing classes to my project and all of them are giving me the last coordinates but not the current ones.
I'm pretty sure that the problem is something fundamental that I am missing but I am not able to understand what exactly it is.
Codes I'm using now:
This is my main Activity
package com.example.locationtests;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GPSTracker mGPS = new GPSTracker(this);
TextView text = (TextView) findViewById(R.id.texts);
if(mGPS.canGetLocation ){
mGPS.getLocation();
text.setText("Lat"+mGPS.getLatitude()+"Lon"+mGPS.getLongitude());
}else{
text.setText("Unabletofind");
System.out.println("Unable");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the class I'm using for Tracking:
package com.example.locationtests;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationtests"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.location" android:required="true" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtests.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Actually GPS positioning works fine, but NETWORK positioning dosn't.
When Ive turned devices GPS on coordinates keep changing while i'm moving, but the same doesn't happen when I have turn it off and relay on the NETWORK_PROVIDER
First you need to define a LocationListener to handle location changes.
int LOCATION_REFRESH_TIME = 15000; // 15 seconds to update
int LOCATION_REFRESH_DISTANCE = 500; // 500 meters to update
....
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager and ask for location updates
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
Hi i am trying to get the device location using the Location api in android using the device network or wifi connection. However it doesnt seem to get the latt or longitude.
i have created a location provider and manager, and registered a location listener.
i then
launched
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
and from that point on, the app doesnt retrieve new location changes at all. what am i missing?
here is my userLocation Code
public class UserLocation implements LocationListener{
public static final int UPDATE_LATT = 0;
private static final int TIME_INTERVAL = 1000;
private static final int DISTANCE = 10;
private LocationManager locationManagaer;
private LocationProvider locationProvide;
private Handler mHandler;
public UserLocation(Context context, Handler handler){
locationManagaer = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationProvide = locationManagaer.getProvider(LocationManager.NETWORK_PROVIDER);
mHandler = handler;
}
public void startSearchLocation(){
Log.d("", "sart location search");
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("", "location update on " + location.getLongitude());
Message.obtain(mHandler,UPDATE_LATT, new Position(location.getLongitude(), location.getLatitude()));
}
#Override
public void onProviderDisabled(String provider) {
Log.d("", "onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("", "onStatusChanged");
}
}
here is my activity that uses this class to setup and listen for new locations
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
position = (Position) msg.obj;
Toast.makeText(
getApplicationContext(),
position.getLattitude() + " " + position.getLongetude(),
Toast.LENGTH_LONG).show();
}
};
userLocation = new UserLocation(this, mHandler);
initializeViews();
userLocation.startSearchLocation();
}
Here is my position POJO
public class Position {
private double longetude;
private double lattitude;
public Position(){
}
public Position(double longetude, double lattitude){
}
public double getLongetude() {
return longetude;
}
public void setLongetude(double longetude) {
this.longetude = longetude;
}
public double getLattitude() {
return lattitude;
}
public void setLattitude(double lattitude) {
this.lattitude = lattitude;
}
}
Here is part of my manifest file
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jr.haliotest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Logcat:
03-23 20:19:14.309: D/(16992): sart location search
03-23 20:19:14.384: E/(16992): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
03-23 20:19:14.384: I/(16992): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.449: I/(16992): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.514: I/(16992): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl
Testing on a htc one x thats rooted if that helps. wifi is on and god signal
If you are within a building then it is probably that your device is not able to connect to a GPS Provider. I would suggest if you move to a more open space so that you can get a signal.
One hint that if the device is connected to receive a gps signal. The sign of the gps will stop blinking and will become solid.
I would start by checking if your phones location services are enabled and maybe try rebooting. Also try using "GPS" instead of "network" to see if the problem is related to your network not providing location info.
From my experience wifi networks will sometimes simply not provide location info. I'm not sure if that's also true for cell networks, but I suspect there is no guarantee.