I have an activity in which I have a text view where I want to display the distance between the user's current location and a specific address. I have the Latitude and Logitude of the address but my issue is getting the user's location. My target is when the activity is created that's when I want to get his location' without pressing any button. I have tried multiple ways: getLastKnownLocation, onLocation changed etc, but the value returned is always null.
It's important to note that I am running the app on an emulator.
Sample code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_list);
Bundle bundleUser = getIntent().getExtras();
final String owneruser = bundleUser.getString("username");
Bundle bundleType = getIntent().getExtras();
String type = bundleType.getString("type");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final TextView t = (TextView) findViewById(R.id.textView2);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
t.append("\n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
final Location userLocation = new Location("");
userLocation.setLatitude(latitude);
userLocation.setLongitude(longitude);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
update();
break;
default:
break;
}
}
void update(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
}
else {
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
}
implement your activity to LocationListener :
public class MyActivity extends AppCompatActivity implements LocationListener {
private Location userLocation = new Location("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
#Override
public void onLocationChanged(Location location) {
if(location != null){
userLocation.setLatitude(location.getLatitude());
userLocation.setLongitude(location.getLongitude());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
TRY this to grant permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
}
}
and add this in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Related
I tried to send my location via SMS, but the button doesn't work.
The button was working fine before I added the code of getting current location.
Can you please help me to fix that? I tried many solutions that I found in this website, but it doesn't work with me.
I am totally new to Android Studio, so I don't know how to write my code that it will work the way I want it.
private LocationManager locationManager;
private LocationListener locationListener;
String[] appPermissions = {
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.SEND_SMS
};
private static final int PERMISSIONS_REQUEST_CODE = 123;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
double x,y;
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkAndRequestPermissons()) {
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
x = location.getAltitude() ;
y = location.getLongitude();
Log.d("Location", location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
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;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxx", null, "Je suis en danger, voici ma localisation : https://www.google.com/maps/search/?api=1&query=" + x + "," + y , null, null);
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
private boolean checkAndRequestPermissons() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions)
{
if (ContextCompat.checkSelfPermission(this,perm) != PackageManager.PERMISSION_GRANTED)
{
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray(
new String[listPermissionsNeeded.size()]),PERMISSIONS_REQUEST_CODE
);
return false;
}
return true;
}
I'm just fetching the current location of the device and displaying on a TextView but the TextView does not show the results, however , it seems that the java code is fetching the location correctly but not updating the TextView as I have tried a lot relevant codes without error of location fetching.
Moreover, I am using a physical device to run the Application, not the emulator.
The recent code I've tried is as below:
public class roadSideSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener, LocationListener {
int MY_PERMISSION_LOCATION=100;
int MY_PERMISSION_ACCESS_COARSE_LOCATION=100;
protected LocationManager locationManager;
protected Context context;
TextView txtLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_side_selection);
marshmallowGPSPremissionCheck();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
txtLat = findViewById(R.id.latitudeTextview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = findViewById(R.id.latitudeTextview);
String s = getString(R.string.latitude, location.getLatitude(), location.getLongitude());
txtLat.setText(s);
}
#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 void marshmallowGPSPremissionCheck() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_LOCATION);
} else {
// gps functions.
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#Nullable String[] permissions,#Nullable int[] grantResults) {
if (requestCode == MY_PERMISSION_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
'''
Strings.xml
Latitude: %1$d; Longitude: %2$d
txtLat = (TextView) findViewById(R.id.latitudeTextview);
Cast the view to TextView and make sure you are using correct view id
I have an app that sends your location on SMS and I need to implement the location.
I tested some code on another project and the code worked well.
I got the code from the test project and made a new class and put the code there but something isn't working.
public class LocMng extends MainActivity {
private Button b;
private TextView t;
private TextView k;
private LocationManager locationManager;
private LocationListener listener;
final int SEND_SMS_PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
b = (Button) findViewById(R.id.btnpol);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
t.append("\n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 10000, 10, listener);
}
});
}
}
When I press the button nothing happens.
Here is the whole file if needed
https://github.com/Tony459/SO-ASt/tree/master/For%20SO
Somethings in the code are Turkish but they are not important
you are not requesting the location correctly , try to get the location this way :
private Location getLastKnownLocation() {
LocationManager mLocationManager;
mLocationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
Your checking code should probably look more like this:
if ( Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
If the 'If' statement is false, then it doesn't return and the b.setOnClickListener gets executed.
I'm very new to android studio, and I'm working with an app that demands more of accuracy of location, first i used location manager but it provides not so accurate location of the user now i want to change it to fused location api but im confused with it, i don't know how to put it in my activity,I already search the net but nothing seems to have sense to me.
here is my Main Activity
public class MainActivity extends AppCompatActivity {
ContactDbAdapter contactDbAdapter;
private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;
#Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
return super.checkUriPermission(uri, pid, uid, modeFlags);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userDbAdapter = new UserDbAdapter(this);
messageText = (EditText) findViewById(R.id.messageText);
locationText = (TextView) findViewById(R.id.locationTextView);
try {
userDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open userDbAdapter\n");
}
contactDbAdapter = new ContactDbAdapter(this);
try {
contactDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open contactDbAdapter\n");
}
cursor = contactDbAdapter.getContacts();
final Button sos = (Button) findViewById(R.id.redbutton);
final Button finish = (Button) findViewById(R.id.greenbutton);
final CountDownTimer timer = new CountDownTimer(3999, 100) {
public void onTick(long millisUntilFinished) {
sos.setText("" + ((int) (millisUntilFinished) / 1000));
}
public void onFinish() {
sos.setVisibility(View.GONE);
finish.setVisibility(View.VISIBLE);
finish.setText("finish");
SmsManager smsManager = SmsManager.getDefault();
cursor = contactDbAdapter.getContacts();
String msg = messageText.getText().toString() + "#" + locationText.getText().toString();
Log.e("mytag", msg);
if(cursor.moveToFirst()){
do{
String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
smsManager.sendTextMessage(number, null, msg, null, null);
}while(cursor.moveToNext());
}
}
};
sos.setTag(1);
sos.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status != 1) {
sos.setText("sos");
sos.setTag(1);
timer.cancel();
} else {
sos.setTag(0);
timer.start();
}
}
}
);
finish.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
sos.setVisibility(View.VISIBLE);
finish.setVisibility(View.GONE);
sos.callOnClick();
}
}
);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.contact:
Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
startActivity(contactIntent);
return true;
case R.id.message:
Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
startActivity(messageIntent);
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onResume() {
super.onResume();
// refresh user message
cursor = userDbAdapter.getUsers();
if (cursor.moveToFirst()) {
messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
}
// Acquire a reference to the system Location Manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null) {
// messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
}
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onDestroy() {
super.onDestroy();
if (cursor != null) {
cursor.close();
}
}
I already put in my manifest the permissions and I also added the 'com.google.android.gms:play-services-location:10.0.0' in my gradle file. The issue now is i want to change the location manager into fused location provider api.
Since location provider is deprecated with LocationProviderClient in latest play services version but if you want to continue with the location provider here is the sample working activity code for location provider in activity
public class LocationActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks,
LocationListener, GetAddressFromLatLng.LocationAddressResponse {
private LocationRequest mLocationRequest;
public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static final int MILLISECONDS_PER_SECOND = 1000;
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create GoogleClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
requestLocationUpdates();
}
}
public void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// runtime permissions
return;
}
locationProvider.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestLocationUpdates();
}
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// every time location changed it calls itself
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PLAY_SERVICES_RESOLUTION_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
requestLocationUpdates();
break;
case Activity.RESULT_CANCELED:
// Do failure task
break;
}
break;
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
requestLocationUpdates();
}
}
}
I am trying to use Google Maps on my app. So far I am able to load the map onto a SupportMapFragment which is called onto my MainActivity as a fragment. However, I am unable to see a blue dot despite enabling locations. I am not able to get the latitude or longitude to show up in the logs as well. Can someone help me with this? I am quite lost. Could it be the permissions I have set? I have also added the necessary permissions in the manifest.
This is my code
public class MapFragment extends SupportMapFragment implements LocationListener,OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleMap googleMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
Location location;
Marker locationMarker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected synchronized void buildGoogleAPIClient(){
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
LatLng currentLocation = new LatLng(location.getLatitude(),location.getLongitude());
Double latitude = currentLocation.latitude;
Double longitude = currentLocation.longitude;
this.location = location;
if(locationMarker!=null){
locationMarker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
locationMarker = googleMap.addMarker(markerOptions);
if(googleApiClient!=null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
buildGoogleAPIClient();
this.googleMap.setMyLocationEnabled(true);
}else{
checkLocationPermission();
}
}else{
buildGoogleAPIClient();
this.googleMap.setMyLocationEnabled(true);
}
}
#Override
public void onPause() {
super.onPause();
if(googleApiClient!=null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);
}
}
private void checkLocationPermission(){
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
//Ask for permission again once the user sees the explanation
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)){
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission required")
.setMessage("This app requires location permissions in order to function")
.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
}else{
//No explanation required. Just request for permissions
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
if(googleApiClient==null){
buildGoogleAPIClient();
}
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
this.googleMap.setMyLocationEnabled(true);
}
}else{
Toast.makeText(getActivity(),"Permission denied",Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Hope someone can help me. Thanks
In the code that you are showing you are never calling getMapAsync on your SupportMapFragment so basically you are just showing a map.
Add getMapAsync to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMapAsync(this);
}
Remember to add the following permissions too:
<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"/>