I am using this code in android 6.0 to get the position:
public class MainActivity extends AppCompatActivity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkPermission())
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
lati = location.getLatitude();
longi = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude", "enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
private boolean checkPermission(){
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 false;
}
return true;
}
}
I set the permissions in the programs properties to true.
It used to work but now it never finds satellites or the position in general.
Google maps immediately finds satellites.
What do I need to change?
see all that TODO comment in your code? implement it. you must do this for it to work on modern versions of andorid
Related
I am making an app with Android Studio where the google maps shows the user's location, and i want to add an acceleration detector so when the acceleration of the user is very large, an alert dialog pops up.
The map with the user's location is working, but when I try to add the acceleration sensor, the app crashes (no error warning). The code is the following:
public abstract class Mapa extends FragmentActivity implements OnMapReadyCallback, SensorEventListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
private SensorManager sensorManager;
Sensor accelerometer;
private SensorManager sensorManager2;
Sensor giroscopio;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorManager.registerListener(Mapa.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float acX;
acX = sensorEvent.values[0];
if (acX >= 10 ){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Warning!");
AlertDialog mensajealerta = builder1.create();
mensajealerta.show();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng posicion = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location ultimaPosicion = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng posicion = new LatLng(ultimaPosicion.getLatitude(), ultimaPosicion.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
}
}
}
I don't understand where the error is, could you help me please?
I finally figured it on my own, so I'll post the answer in case anyone else may need it.
Apparently it does not work when you put the Google maps and the accelerometer in the same activity, so I had to separate them. Ir order to do so, I used a Service for detecting the acceleration.
I managed to get my Service going by looking at this:
Android sensors not working in a service
Once this is done, I send my accelerometer info to my maps activity with a LocalBroadcastManager:
How to use LocalBroadcastManager?
By following the instructions given in these 2 questions I managed to make it work.
I'm working with the map to my app and so I have here a weird error message that it says java.lang.SecurityException: "GPS" location provider requires ACCESS_FINE_LOCATION permission. every time I launch the app and crashes due to this error, though I already have a permission checker.
Here is my code:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "SOME_KEY";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
getUserLocation();
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
I really do not know where I went wrong from this line of code, to keep my app crashing and give me that error.
Update your code with bellow code may solve your problem
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
boolean isMapReady;
#Override
public void onMapReady(GoogleMap googleMap) {
isMapReady=true;
getUserLocation();
}
private void getUserLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
return;
}
}
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
Now override onRequestPermissionsResult() and check if result is granted and isMapReady flag true then call getUserLocation().
So the solution for this and base on the comments i forgot to put the else statement that if the permission is granted then execute the listener else request a permission.
Updated:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
checkGPSPermission();
getUserLocation();
}
private void checkGPSPermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
// show why is important
}
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
// granted
}
} else {
// granted
}
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
}
So I've tried to get the users location and wanted it to popup as a Toast() or in the Logs but nothing happens.
I've added <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> to the manifest and this is my class:
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the users location
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("LOCATION", location.toString());
Toast.makeText(MainActivity.this, location.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
Log.i("STATUS", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
// Ask users permission to get location
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
}
}
The app asks for permission the first time and after I accept it doesn't show any signs of getting a location from the OnStatusChanges() method. I've tried to get lastKnownLocation()and it works but that's all...
Any idea what's missing?
Thanks!
I'm making an app and I'm using Googlemaps.
Below is my code
I have tried so many different codes but nothing works
My app doesn't work and keeps getting this error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.yoons.honey.Map.onCreate(Map.java:59)
xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Map"
tools:layout_editor_absoluteY="81dp">
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:id="#+id/button"
android:text="my location"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.imaadv.leaynik.ClinicFragment"
android:layout_below="#+id/button"/>
/>
activity code :
public class Map extends AppCompatActivity {
private static final String TAG = "MainActivity";
SupportMapFragment mapFragment;
GoogleMap map;
MarkerOptions myLocationMarker;
private CompassView mCompassView;
private SensorManager mSensorManager;
private boolean mCompassEnabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() { //This is the error I think
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "GoogleMap is ready.");
map = googleMap;
onResume();
map.setMyLocationEnabled(true);
}
});
try {
MapsInitializer.initialize(this);
} catch (Exception e) {
e.printStackTrace();
}
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestMyLocation();
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
boolean sideBottom = true;
mCompassView = new CompassView(this);
mCompassView.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
((ViewGroup) mapFragment.getView()).addView(mCompassView, params);
mCompassEnabled = true;
}
private void requestMyLocation() {
LocationManager manager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
long minTime = 10000;
float minDistance = 0;
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
minTime,
minDistance,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
showCurrentLocation(lastLocation);
}
manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
minTime,
minDistance,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void showCurrentLocation(Location location) {
LatLng curPoint = new LatLng(location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));
showMyLocationMarker(location);
}
private void showMyLocationMarker(Location location) {
if (myLocationMarker == null) {
myLocationMarker = new MarkerOptions();
myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
myLocationMarker.title("�뿈 �궡 �쐞移?n");
myLocationMarker.snippet("�뿈 GPS濡� �솗�씤�븳 �쐞移�");
myLocationMarker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mylocation));
map.addMarker(myLocationMarker);
} else {
myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
}
}
#Override
protected void onPause() {
super.onPause();
if (map != null) {
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;
}
map.setMyLocationEnabled(false);
}
if (mCompassEnabled) {
mSensorManager.unregisterListener(mListener);
}
}
#Override
protected void onResume() {
super.onResume();
if (map != null) {
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;
}
map.setMyLocationEnabled(true);
}
if(mCompassEnabled) {
mSensorManager.registerListener(mListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
}
}
private final SensorEventListener mListener = new SensorEventListener() {
private int iOrientation = Surface.ROTATION_0;
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (iOrientation < 0) {
iOrientation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
}
mCompassView.setAzimuth(event.values[0] + 90 * iOrientation);
mCompassView.invalidate();
}
};
}
I looked through a lot of questions like this.
I tried inflating my view but when I tried
View view = inflater.inflate(R.layout.map, null, false);
the inflater had a red line to it. It said it couldn't resolve symbol 'inflater'
and also when I tried getChildFragmentManager instead of getSupportFragmentManager I also had a red line
And I think I have got all the users-permissions
Used this code on previous app and all seems ok - but today im getting a
call requires permission which may be rejected by user
I have added
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
to manifest and have read several threads on the subject, but still having issues. Could you guys helps out.
public class MainActivity extends AppCompatActivity implements LocationListener
{
private LocationManager locationManager;
public static String locationlong;
public static String locationlati;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.pig);
TextView cow = (TextView)findViewById(R.id.cow);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
}
}
Add the permission check in your activity:
in your code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.pig);
TextView cow = (TextView) findViewById(R.id.cow);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkLocationPermission()) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
}
}
public boolean checkLocationPermission() {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 0: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
Basically since android 6 you need to ask certain permissions on runtime , so the user may reject them.
Use checkSelfPermission(..) to ask for it and override onRequestPermissionsResult to see the answer.
Here's a link with the full example:
https://developer.android.com/training/permissions/requesting.html