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" />
Related
I have a problem with my GPS Location App I have tried by all means and I can't find the solution (I'm developing in Android 6.0) , this is the problem:
"network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission
this is my XML FIle:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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_LOGS" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".chooseEmergency"></activity>
</application>
And this is my LocationManager Code:
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
(LocationListener) Local);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//use checkSelfPermission()
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
} else {
//simply use the required feature
//as the user has already granted permission to them during installation
}
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
public class Localizacion implements LocationListener {
MainActivity mainActivity;
public MainActivity getMainActivity() {
return mainActivity;
}
public void setMainActivity(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public void onLocationChanged(Location loc) {
latitud = loc.getLatitude();
longitud = loc.getLongitude();
this.mainActivity.setLocation(loc);
}
#Override
public void onProviderDisabled(String provider) {//pndiente de escribir;
}
#Override
public void onProviderEnabled(String provider) {//pendiente
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Please help, I took 2 days looking at internet solutions and nothing works for me
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
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.
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 m using google maps v2 and getting this error.
Could not find class 'maps.af.k', referenced from method maps.ag.an.a
I m following all the rules correctly. I have created SHA1 finger print and added it to ANdroid Key for apikey with projct name
1F:41:29:EC:E8:07:3C:A9:F8:6E:EB:D2:7B:42:41:62:3A:36:CA:F2;com.example.routes
Then in mainest file i m using
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
i have also imported the googleplayservices and correctly added it to the project
My code is
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = new SupportMapFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
;
googleMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
}
}
but still i m getting that error.
Try to extend Activity rather then FragmentActivity:
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager;
private GoogleMap googleMap;
double lat=17.385044;
double long=78.486671;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service=(LocationManager)getSystemService(LOCATION_SERVICE);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
private void initilizeMap(){
if(googleMap==null){
googleMap=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
//check if map is created succesfully or not
if(googleMap==null){
Toast.makeText(getApplicationContext(),"sorry unable to create map",1).show();
}
}
MarkerOptions markerOptions=new MarkerOptions().position(new LatLng(lat,long));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
CameraPosition cameraPosition=new CameraPosition.Builder().target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.setMyLocationEnabled(true);
googleMap.setOnInfoWindowClickListener(null);
}
#Override
protected void onResume(){
super.onResume();
initilizeMap();
}
I had the same problem and my solution was to remove and add the googleplayservices again.
When you are using SupportMapFragment no need of extending FragmentActivity just extend the Activity See the below example code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
public class MainActivity extends Activity {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
#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;
}
}
Note: You have to add google play services library project as a reference to your project, your package name must be com.example.routes you have to add the map fragment in your xml layout not in the manifest.
Make following changes to your Manifest.xml
Add following permissions.
<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.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Add the OpenGL
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
Add the API key
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>
Example manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<used-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.package.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>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR_API_KEY_HERE"/>
</application>