I'm trying to develo an app that get location by COARSE location. This app must run on Android 6 too than i've implemented permission request on run time, start the map but i can't get my current location... any tips?
This is my main activity:
package com.luca.fontanelle;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.location.LocationListener;
import android.Manifest;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
final static int REQUEST_LOCATION = 199;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private String providerNetwork = LocationManager.NETWORK_PROVIDER;
private Location mCurrentLocation;
private LocationRequest mLocationRequest;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_LOW_POWER)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected void onStart() {
super.onStart();
}
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
protected void onStop() {
super.onStop();}
protected void onDestroy() {
super.onDestroy();
}
public void onLocationChanged(Location location) {
mCurrentLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude())));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15.0f));
}
public void onConnected(Bundle bundle) {
if (controllaPermessi()) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//...
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
/* 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;
}*/
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}else{
richiestaPermessi();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
//Log.d("MapsActivity", "Connessione fallita. Codice di errore: " + connectionResult.getErrorCode());
}
}
private boolean controllaPermessi(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void richiestaPermessi(){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)){
Toast.makeText(getApplicationContext(), "Attiva la localizzazione per usufruire dell'app.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permessi accettati. Puoi usare tutte le funzionalità.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Permessi non accettati. Non puoi accedere alle funzionalità del GPS.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.luca.fontanelle">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<permission
android:name="com.luca.fontanelle.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission-sdk-23 android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
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" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<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>
</application>
</manifest>
Try this code with google fused location api
1) MainActivity.class
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String mLastUpdateTime;
private boolean mycheck, chrckonce;
private LocationManager manager;
private Double lat, lng;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
chrckonce = true;
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
if (!manager.isProviderEnabled((LocationManager.GPS_PROVIDER))) {
//GPS is not available show alert
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enable! Want to go to settings menu?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(" Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
finish();
}
});
alertDialog.show();
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mycheck = true;
buildGoogleApiClient();
mGoogleApiClient.connect();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
lat = location.getLatitude();
lng = location.getLongitude();
if (chrckonce) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)), 2000, null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 18));
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
chrckonce = false;
}
}
//Update location from google fused api
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
}
}
//synchronized google fused location api
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
//create location request
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//on resume activity
#Override
public void onResume() {
super.onResume();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
}
//when activity goes on pause
#Override
protected void onPause() {
super.onPause();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
}
//when activity stops
#Override
protected void onStop() {
if (mycheck == true) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
startLocationUpdates();
}
//check connection suspended
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
//Location update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
//location update close when activity closed
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
2) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
In Manifest permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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"/>
Related
I can't access my current location with this. I don't know what is the problem but. Every time I go to the map fragment on my navigation bar I can't see my current location.
Here is my code..
LanlordMapFragment.java
public class LanlordMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
public LanlordMapFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_lanlord_map, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("MAP");
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("My Location"));
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
return;
}
}
}
I've also experienced such type of problem:
Please, try to add the piece of code to your public View onCreateView(..){}
MapView m = (MapView) v.findViewById(R.id.source);
m.onCreate(savedInstanceState);
//try this code
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
{
#Override
public void onMapClick(LatLng latLng)
{
}
});
GetCurrentLocation location = new GetCurrentLocation(getActivity(), new GeocodingNotifier<Location>()
{
#Override
public void GeocodingDetails(Location geocodeLatLng) {
if (geocodeLatLng != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(geocodeLatLng.getLatitude(), geocodeLatLng.getLongitude()), 14f));
}
else {
// shaow erroe message
}
}
});
/// class to GetCurrentLocation
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class GetCurrentLocation implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
private static final String TAG = GetCurrentLocation.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
public static Location mLastLocation=null;
public GoogleApiClient mGoogleApiClient;
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
private GeocodingNotifier mNotifier;
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
Activity mContext;
public GetCurrentLocation(Activity mContext, GeocodingNotifier mNotifier) {
this.mContext = mContext;
this.mNotifier = mNotifier;
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
public void setOnResultsListener(GeocodingNotifier mNotifier) {
this.mNotifier = mNotifier;
}
/**
* Method to display the location on UI
*/
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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;
}
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
}
}
/**
* Method to toggle periodic location updates
*/
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
} else {
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
displayLocation();
}
/**
* Method to verify google play services on the device
*/
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(mContext);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, mContext,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(mContext,
"This device is not supported.", Toast.LENGTH_LONG)
.show();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
public void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
public void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
mNotifier.GeocodingDetails(mLastLocation);
displayLocation();
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
}
In my application the location updates are not working and the app get closed when i click on start location updates button. I am a beginner i doesnt know how to debug this error.What i want from my application is
the application must updates the location on every minutes
the application will work on background and it will close when we close the applications like music player
Main_activity.class
package com.example.admin.locationapidemo;
import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.sql.Connection;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
- List item
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private boolean mRequestLocationUpdates = false;
private LocationRequest mLocationRequest;
private static int UPDATE_INTERVAL = 10000;
private static int FATEST_INTERVAL = 5000;
private static int DISPLACEMENT = 10;
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.buttonShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.buttonLocationUpdates);
if(checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePeriodLocationUpdates();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
if(mGoogleApiClient.isConnected() && mRequestLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if(mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longtitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longtitude);
} else {
lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
}
}
private void togglePeriodLocationUpdates() {
if(!mRequestLocationUpdates) {
btnStartLocationUpdates.setText(getString(R.string.btn_stop_location_updates));
mRequestLocationUpdates = true;
startLocationUpdates();
} else {
btnStartLocationUpdates.setText(getString(R.string.btn_start_location_updates));
mRequestLocationUpdates = false;
stopLocationUpdates();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS) {
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnected(Bundle bundle) {
displayLocation();
if(mRequestLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show();
displayLocation();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: " + connectionResult.getErrorCode());
}
}
My xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#color/view_bg">
<TextView
android:text="#string/lbl_you_are_at"
android:layout_marginTop="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="25dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/lblLocation"
android:padding="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="16dp" />
<Button
android:id="#+id/buttonShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#color/btn_bg"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="#string/btn_get_location"
android:textColor="#color/view_bg"/>
<Button
android:id="#+id/buttonLocationUpdates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:background="#color/btn_bg"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="#string/btn_start_location_updates"
android:textColor="#color/view_bg"/>
</LinearLayout>
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.locationapidemo">
<uses-permission android:name="android.permission.ACCESS_FINE_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">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longtitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longtitude);
} else {
lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
}
}
remove this line
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
because in onLocationChanged() you are assigning value to mLastLocation, so try to use that assigned value.
This is the code i have created and is simple activity that shows current location of user art regular intervals on a button click. I want to make it a service so that when i click on button, it starts the service that keeps on fetching the user's current location but i am not able to do that. Can some one help me in doing it. This is the code for MainActivity.java.
package com.maps.saury.location;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
BGTask bgtask=new BGTask(this);
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 100; // 10 sec
private static int FATEST_INTERVAL = 100; // 5 sec
private static int DISPLACEMENT = 0; // 10 meters
// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
// Show location button click listener
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
// Toggling the periodic location updates
btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePeriodicLocationUpdates();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
/**
* Method to display the location on UI
* */
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
BGTask bgtask=new BGTask(this);
bgtask.execute(Double.toString(latitude),Double.toString(longitude));
} else {
lblLocation
.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
/**
* Method to toggle periodic location updates
* */
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_stop_location_updates));
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
} else {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_start_location_updates));
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
* */
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
* */
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
* */
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Locatn changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
}
This is my Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/view_bg"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="60dp"
android:src="#drawable/marker" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="#string/lbl_you_are_at"
android:textColor="#color/white"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lblLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="15dp"
android:textColor="#color/white"
android:textSize="16dp" />
<Button
android:id="#+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#color/btn_bg"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="#string/btn_get_location"
android:textColor="#color/white" />
<Button
android:id="#+id/btnLocationUpdates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:background="#color/btn_bg"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="#string/btn_start_location_updates"
android:textColor="#color/white" />
</LinearLayout>
First Check your Manifest.xml and check Internet permission.
<permission
android:name="com.hamms.cabsystem.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
Second Check google Map Api Meta data.
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBBGHOC13C00ew4xKD7kyei0M3bul8093s" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Then, Create on ServiceClass like this and start Service on click of button.
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(this,MyService.class));
}
}
public class MyService extend Service{
onstartCommand(){
Intent i = new Intent(youraction);
sendBroadCast(i);
}
In Myservice onStartCommand Method Send OneBraodcast which is update your location.
Register Brodcast Receiver in Manifest,xml
<receiver android:name="MyBroadCast"></receiver>
public class MyBroadCast extend BrodcastReciver{
// here onRecive Method you upadate your location.
// do something here //
}
I have an activity called LocationTest and in my application that get the latitude and longitude and it is working properly.This activity includes a button that take us to another activity that called MapLocation that shows graphically the location on a map.But when I click the app will stop working.I will post the code of the 2 activities if somebody can help plz.I think the error is in the second activity
LocationTest Activity
public class LocationTest extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
public final static int MILLISECONDS_PER_SECOND=1000;
public final static int MINUTE = 60*MILLISECONDS_PER_SECOND;
private double longitude=0;
private double latitude=0;
private TextView lblLong;
private TextView lblLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_test);
//this here is for the map
Button mapBtn =(Button)findViewById(R.id.mapBtn);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(LocationTest.this,MapLocation.class);
startActivity(intent);
}
});
locationRequest= new LocationRequest();
/*locationRequest.setInterval(MINUTE);*/
locationRequest.setInterval((MINUTE));
locationRequest.setFastestInterval(15 * MILLISECONDS_PER_SECOND);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lblLong = (TextView)findViewById(R.id.lblLong);
lblLat = (TextView)findViewById(R.id.lblLat);
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
#Override
protected void onResume() {
super.onResume();
if(googleApiClient.isConnected()){
requestLocationUpdates();
}
}
#Override
public void onConnected(Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this, "Your Location Has Been Set: " + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_LONG).show();
longitude = location.getLongitude();
latitude = location.getLatitude();
lblLong.setText(Double.toString(longitude));
lblLat.setText(Double.toString(latitude));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
MapLocation Activity
public class MapLocation extends AppCompatActivity implements LocationListener{
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_map_location);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
In order to show a map in your app, you will need the following steps:
1) Get you API key from https://developers.google.com/maps/documentation/android-api/ and set your permissions like this in your manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Your package name" >
...
<!-- Creating Permission to receive Google Maps -->
<permission
android:name="com.arshad.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Permission to receive Google Maps -->
<uses-permission android:name="com.arshad.map.permission.MAPS_RECEIVE" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
...
<!-- Maps API -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Replace with your API key" />
...
</application>
</manifest>
2) Here is an example using fragments:
import android.Manifest;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import R;
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final String ARG_LONGITUDE = "longitude";
private static final String ARG_LATITUDE = "latitude";
private static final String LOG_TAG = MapFragment.class.getSimpleName();
private String mLongitude;
private String mLatitude;
//Google maps parameters initialization
static LatLng location = new LatLng(21, 57);
public static MapFragment newInstance(String longitude, String latitude) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_LONGITUDE, longitude);
args.putString(ARG_LATITUDE, latitude);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
//Get lattitude and longitude
mLongitude = getArguments().getString(ARG_LONGITUDE);
mLatitude = getArguments().getString(ARG_LATITUDE);
Log.d(LOG_TAG, "Long = " + mLongitude + " lat = " + mLatitude);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
MapFragment mapFragment = new MapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.rl_map_container, mapFragment).commit();
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap map) {
//Setting the position of camera in the important location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude)), 17));
//Adding a marker with customized icon
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_<Your icon name>))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude))));
// MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID and MAP_TYPE_NONE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
3) Make your layout like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".fragments.MapFragment"
>
<FrameLayout
android:id="#+id/rl_map_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Also, you can get more information in https://developers.google.com/maps/documentation/android-api/
I'm working on a location based tracking app. Does anyone know how to use only gps location and not network provider location. Since i'm using acess_fine_location in my manifest it uses both.
This is my tracking code:
package com.persasrl.paul.quickfit;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
GoogleApiClient mGoogleApiClient;
TextView mDistanceText;
TextView mTimeText;
Location mLastLocation;
Location mCurrentLocation;
UserLocalStore userLocalStore;
float[] d = new float[1];
float totald=0;
int type;
private MCountDownTimer countDownTimer;
private long timeElapsed;
private final long startTime = 9223372036854775807L;
private final long interval = 1;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
userLocalStore = new UserLocalStore(this);
mDistanceText = (TextView) findViewById(R.id.dist);
mTimeText = (TextView) findViewById(R.id.time);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
Intent startIntent = getIntent();
Bundle bundle = startIntent.getExtras();
if(bundle!=null)
type= bundle.getInt("sport");
isGpsConnected();
createLocationRequest();
buildGoogleApiClient();
}
public void isGpsConnected()
{
// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void stopApp(View view)
{
User user = userLocalStore.getLoggedInUser();
Workout workout = new Workout (totald,type,user.username,timeElapsed);
registerWorkout(workout);
}
private void registerWorkout(Workout workout) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeWorkoutDataInBackground(workout, new GetWorkoutCallback() {
#Override
public void done(Workout returnedWorkout) {
Intent Intent = new Intent(StepCounter.this, MainActivity.class);
startActivity(Intent);
}
});
}
public void onConnected(Bundle connectionHint) {
countDownTimer = new MCountDownTimer(startTime, interval);
countDownTimer.start();
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(500);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
if(mCurrentLocation!=null)
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
if(mLastLocation!=null && mCurrentLocation!=null)
updateDistance();
}
public void updateDistance()
{
Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), d);
if(!(d[0]<0.001))
totald+=d[0];
mDistanceText.setText(String.valueOf(String.format("%.3f", totald)));
}
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
//timer
public class MCountDownTimer extends CountDownTimer
{
public MCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
mTimeText.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished)
{
long hours=0;
long minutes=0;
long seconds=0;
timeElapsed = (startTime - millisUntilFinished)/1000;
seconds= timeElapsed%60;
minutes= timeElapsed/60%60;
hours = timeElapsed/3600;
mTimeText.setText(String.valueOf(hours) + ":" + String.valueOf(minutes)+ ":" + String.valueOf(seconds));
}
}
}
And my manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
//android:theme="#android:style/Theme.Holo"
<activity
android:name=".LoginScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<activity
android:name=".StepCounter"
android:label="#string/title_activity_step_counter" >
</activity>
</application>