There are some questions regarding this issue but I could not find any method works without problem. I implemented the version of the project with GPS provider and now I want to implement a version which can find the location of user without GPS, just using network provider such as Wifi. I tried this but it is not working (I could not get the "done" message in any way):
public class MapsActivity extends FragmentActivity {
double latitude;
double longitude;
LocationManager locationManager;
android.location.LocationListener networkLocationListener;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
networkLocationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("->", "done.");
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
}
...
Also, this is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.doruk.myapplication">
<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" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/orange"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
Can you see the problem? What you advise at this point? Is there a better way?
Dorukhan Arslan
- You can use GoogleclientAPi, as locationmanager has been
Deprecated
-Using FusedLocationAPi it will automatically discover the provider to find the location.
- https://developer.android.com/google/auth/api-client.html have a look
on this
- Here is one exampleprotected void createLocationRequest() {
LocationRequest mLocation = LocationRequest.create();
GoogleAPiClient mgoogle;
/*enter code here
* Set the update interval
*/
mLocation.setSmallestDisplacement(500); // 2km
mLocation.setInterval(180000);// 3 min
mLocationRequest.setFastestInterval(120000);// 2 min
mLocation.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (mgoogle == null) {
mgoogle = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mgoogle.connect();
}
}
It's a sample and implementing OnConnectionFailedListener,
ConnectionCallbacks, com.google.android.gms.location.LocationListener above 3 interfaces you can get the continuos Location.
getLastLocation Method Of LocationRequest Class will give you Location.
onLocationChanged Method will give you Your desired output.
You can use IP address of user for getting approx location.
Related
Hello i am new to android development . I want to get my current Location but i need to wait for my listener start working . The problem is that i dont change position so the listener cant work (?) !
Here is the sample of my code
My listener :
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append(location.getLongitude() + "\n" + location.getLatitude() + "\n");
// just monitoring
lat = location.getLatitude();
lng = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
and i request the updates on this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300, 0, locationListener);
So if i am not mistaken the gps will take the new position based on time (300ms) or based on distance which is 0 so its gonna work ?? Should i wait some time to start taking it? How long? more than 2 minutes?
I got wi-fi open and gps of course this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Details" />
<activity android:name=".LoginMenu" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity android:name=".Road" />
<activity android:name=".LoopActivity" />
<activity android:name=".Pedestrians"></activity>
</application>
Many Thanks in regards
I am using the below code to obtain the location of a user
public class MainLocation extends Application implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
String lat;
String provider;
protected String latitude, longitude;
protected boolean gps_enabled, network_enabled;
#Override
public void onCreate() {
super.onCreate();
Log.e("Location", "here");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
Log.e("Location", "" + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("Location Status", "" + provider + " " + status + " " + extras);
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Location", "Enabled");
}
#Override
public void onProviderDisabled(String provider) {
Log.e("Location","Disabled"+provider);
}
}
but here the onLocationChanged function is never getting called, so i m not able fetch the location. So how can i get the location?
In the logcat, the info tab is showing the latitude and longitude under the title onLocationReceived".
This is the manifest,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.krijjj.loginapp" >
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-sdk android:minSdkVersion="15" />
<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" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".Location.MainLocation"
android:allowBackup="true"
android:icon="#drawable/icon1"
android:label="#string/app_name"
android:theme="#style/AppTheme"
tools:replace="android:label" >
<activity
android:name=".Track"
android:label="Track" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Security.Lockscreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Second"
android:label="#string/title_activity_second" >
<intent-filter>
<action android:name="com.example.krijjj.loginapp.Second" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/title_activity_mapactivity" >
</activity>
<activity
android:name=".Security.MainActivity"
android:label="#string/title_activity_mapactivity" >
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
</application>
</manifest>
The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app.
You can find the example how to use it right here.
P.S. Don't forget to check if permissions granted on your device, if you added permissions into manifest file...
I'm litte ashamed. But cant find what's wrong.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.szymon.gpslab1"
android:versionCode="15"
android:versionName="4.0.3">
<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"/>
<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"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
It's my manifest.
and here's my code:
public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
System.out.println("ZMIENIAMY SIĘ, zmieniamy siebie");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
}
Im using the newest android studio (intellij) with embedded (?) emulator. Phone is out of options.
ANd here what i've got:
FATAL EXCEPTION: main
Process: com.example.szymon.gpslab1, PID: 3274
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.szymon.gpslab1/com.example.szymon.gpslab1.MainActivity}: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
Caused by: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
I belive this is stupid mistake, but I've never like developed for android, im the javaman, and i've reached every tutorial on net, cant find answer.
Ah and y, I have location on in my emulator.
This is a common exception if your target SDK is 23 in your build.gradle.
Android 6.0 / sdk 23 introduces a new way of requesting permissions.
See the link below for how to handle permissions:
https://developer.android.com/training/permissions/index.html
i am new to android.i need to get lattitude and logitude of current location.but it shows null pointer exception in location.here below i added my code.
LocationManager lm;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
SaveLocation(location);
}
private void SaveLocation(Location location) {
Long time=new GregorianCalendar().getTimeInMillis()+1*60*1000;
Intent intent=new Intent(MainActivity.this,AlarmReceiver.class);
intent.putExtra("lat",location.getLatitude());
intent.putExtra("lon",location.getLongitude());
AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,time,PendingIntent.getBroadcast(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT));
}
my androidmanifasted file is like
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.gps.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>
Anyone can help me?
Your location is null because you instantly try to get the last known location after you create a LocationManager. In this time (some milliseconds) your device can't find any locations.
You need a time gap between your initalization of your LocationManager and the getLastKnownLocation-method. I would recommend to put the getLastKnownLocation-method in an OnClick event on a button to create a time gap.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
/....
}
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
SaveLocation(location);
}
});
Your Location object is null, since there is no last known location stored.
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Check if last known location exists.
if(location != null) {
SaveLocation(location);
}
//to find the current latitude and longitude of user
public String getMyLocation(){
locationManager=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null){
loc[0]=location.getLatitude();
loc[1]=location.getLongitude();
Log.d("STATUS n ", loc[0]+"entered 1"+loc[1]);
}
else {
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
loc[0]=location.getLatitude();
loc[1]=location.getLongitude();
Log.d("STATUS n","else"+loc[0]+"entered 1"+loc[1] );
}
}
return getPlace(loc);
}
I am very new to Android development. So forgive this repetitive question. I've tried many of the solutions on this but none seem to work quite right for me...They all crash on emulator and on my phone.
I'm working on an App and just want to get my GPS Location and then sets the TextView called 'big' to the location's value.
Heres the code. (I have the import statements and everything in my code..I just didnt copy them over
GPSActivity //the activity that starts. the textview R.id.big does exist
public class GPSActivity extends Activity{
private LocationManager manager = null;
private MyLocationListener listener;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new MyLocationListener(textView);
textView = (TextView) findViewById(R.id.big);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener(textView);
manager.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,listener);
}
}
I implemented my own LocationListener that changes my TextView...I'm not sure if I'm really allowed to do this....
public class MyLocationListener implements LocationListener
{
TextView textView;
public MyLocationListener(TextView textView)
{
this.textView = textView;
}
#Override
public void onLocationChanged(Location location) {
this.textView.setText(location.toString());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
Lastly my manifest file. I made sure to include the permissions I needed.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mytestapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<activity
android:name="com.mytestapp.GPSActivity"
android:permission="ACCESS_FINE_LOCATION"
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>
The problem occurs in GPSActivity when I call requestLocationUpdates(). The app crashes if I leave this line in the code. If I comment it out, the TextView 'big' displays like I would expect it to.
edit: I've also tried creating a LocationListener as an inner-class like I've seen a lot of other people do on SO...and I had the same result (app crash)
Add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
to your manifest.xml file.
for a complete support of Geolocation using GPS or WiFi use:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
and for the devices that don´t have support for gps use:
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
In addition to the ACCESS_FINE_LOCATION permission try adding
ACCESS_GPS
and they should look like this ...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />