Commit eb54a43c authored by Vytor Calixto's avatar Vytor Calixto 👾
Browse files

Substituição de código da Google Play para sensor

Há muito a ser feito ainda para se usar a Google Play para se obter
a localização, por isso essa versão apenas usa o sensor GPS.
parent a07c100b
...@@ -17,5 +17,8 @@ ...@@ -17,5 +17,8 @@
</intent-filter> </intent-filter>
</activity> </activity>
</application> </application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest> </manifest>
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
* Created on 20/04/2015.
public class EnableGpsDialogFragment extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
.setPositiveButton(R.string.dialog_enable_gps, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return builder.create();
package; package;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location; import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle; import android.os.Bundle;
import android.os.StrictMode;
import; import;
import android.util.Log; import android.util.Log;
import android.view.Menu; import android.view.Menu;
...@@ -14,34 +23,53 @@ import; ...@@ -14,34 +23,53 @@ import;
import; import;
import; import;
public class MainActivity extends ActionBarActivity
implements ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
protected static final String TAG = "geoloc"; public class MainActivity extends ActionBarActivity implements LocationListener {
/** protected static final String TAG = "geoloc";
* Provê o acesso a API do google
protected GoogleApiClient mGoogleApiClient;
/** /**
* Última localização obtida através da api * Última localização obtida
*/ */
protected Location lastLocation; private Location lastLocation;
private LocationManager locationManager;
protected TextView latitudeText; private TextView latitudeText;
protected TextView longitudeText; private TextView longitudeText;
private String provider;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
//Pegamos a referência as TextViews que vamos modificar
latitudeText = (TextView) findViewById(; latitudeText = (TextView) findViewById(;
longitudeText = (TextView) findViewById(; longitudeText = (TextView) findViewById(;
buildGoogleApiClient(); //Construímos o locationManager e pegamos o serviço em execução
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Se o GPS não estiver habilitado alertamos o usuário com uma dialog para que ele habilite
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
DialogFragment dialog = new EnableGpsDialogFragment();, "habilitar gps");
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
lastLocation = locationManager.getLastKnownLocation(provider);
if(lastLocation != null){
Log.d(TAG, "Provedor " + provider + " foi selecionado.");
} }
@Override @Override
...@@ -66,50 +94,40 @@ public class MainActivity extends ActionBarActivity ...@@ -66,50 +94,40 @@ public class MainActivity extends ActionBarActivity
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
/** /* Request updates at startup */
* Constrói o objeto que faz a conexão a API @Override
*/ protected void onResume() {
protected synchronized void buildGoogleApiClient() { super.onResume();
mGoogleApiClient = new GoogleApiClient.Builder(this) locationManager.requestLocationUpdates(provider, 400, 1, this);
} }
/* Remove the locationlistener updates when Activity is paused */
protected void onPause() {
//Métodos implementados de ConncetcionCallbacks @Override
public void onLocationChanged(Location location) {
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
latitudeText.setText("Latitude:" + String.valueOf(lat));
longitudeText.setText("Longitude" + String.valueOf(lng));
* Runs when a GoogleApiClient object successfully connects.
@Override @Override
public void onConnected(Bundle connectionHint) { public void onStatusChanged(String provider, int status, Bundle extras) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (lastLocation != null) {
latitudeText.setText("Latitude: "+String.valueOf(lastLocation.getLatitude()));
longitudeText.setText("Longitude: "+String.valueOf(lastLocation.getLongitude()));
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
} }
@Override @Override
public void onConnectionSuspended(int cause) { public void onProviderEnabled(String provider) {
// The connection to Google Play services was lost for some reason. We call connect() to Log.d(TAG, "Novo provedor habilitado: " + provider);
// attempt to re-establish the connection.
Log.i(TAG, "Conexão suspensa");
} }
@Override @Override
public void onConnectionFailed(ConnectionResult result) { public void onProviderDisabled(String provider) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in Log.d(TAG, "Provedor desabilitado: " + provider);
// onConnectionFailed.
Log.i(TAG, "Conexão falhou: ConnectionResult.getErrorCode() = " + result.getErrorCode());
} }
} }
...@@ -4,4 +4,8 @@ ...@@ -4,4 +4,8 @@
<string name="hello_world">Hello world!</string> <string name="hello_world">Hello world!</string>
<string name="action_settings">Configurações</string> <string name="action_settings">Configurações</string>
<string name="no_location_detected">Não foi detectada uma localização</string> <string name="no_location_detected">Não foi detectada uma localização</string>
<string name="dialog_enable_gps_message">Por favor, habilite o GPS.</string>
<string name="dialog_warn">Aviso</string>
<string name="dialog_enable_gps">Habilitar o GPS</string>
<string name="cancel">Cancelar</string>
</resources> </resources>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment