Hola,
Descargue el código fuente desde aquí ( Obtener la ubicación actual utilizando el servicio en segundo plano ).
AndroidManifest.xml
http://schemas.android.com/apk/res/android" ;
package = “servicetutorial.service”>
android: allowBackup = “true”
android: icon = “@ mipmap / ic_launcher”
android: label = “@ string / app_name”
android: supportsRtl = “true”
android: theme = “@ style / AppTheme”>
android: theme = “@ android: style / Theme.Translucent.NoTitleBar”>
activity_main.xml
http://schemas.android.com/apk/res/android" ;
android: layout_width = “match_parent”
android: background = “# ffffff”
android: layout_height = “match_parent”>
android: layout_width = “match_parent”
android: layout_height = “50dp”
android: background = “# 3F51B5”
android: text = “Ubicación usando el servicio”
android: textColor = “# ffffff”
android: textSize = “20dp”
android: gravity = “center” />
android: layout_width = “match_parent”
android: layout_height = “wrap_content”
android: layout_centerInParent = “true”
android: orientación = “vertical”>
android: layout_width = “match_parent”
android: orientación = “horizontal”
android: layout_height = “50dp”>
android: layout_width = “150dp”
android: layout_height = “wrap_content”
android: text = “Latitud”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “wrap_content”
android: layout_height = “wrap_content”
android: text = “”
android: id = “@ + id / tv_latitude”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “match_parent”
android: orientación = “horizontal”
android: layout_height = “50dp”>
android: layout_width = “150dp”
android: layout_height = “wrap_content”
android: text = “Longitud”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “wrap_content”
android: layout_height = “wrap_content”
android: text = “”
android: id = “@ + id / tv_longitude”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “match_parent”
android: orientación = “horizontal”
android: layout_height = “50dp”>
android: layout_width = “150dp”
android: layout_height = “wrap_content”
android: text = “Dirección”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “wrap_content”
android: layout_height = “wrap_content”
android: text = “”
android: id = “@ + id / tv_address”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “match_parent”
android: orientación = “horizontal”
android: layout_height = “50dp”>
android: layout_width = “150dp”
android: layout_height = “wrap_content”
android: text = “Área”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “wrap_content”
android: layout_height = “wrap_content”
android: text = “”
android: id = “@ + id / tv_area”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “match_parent”
android: orientación = “horizontal”
android: layout_height = “50dp”>
android: layout_width = “150dp”
android: layout_height = “wrap_content”
android: text = “Localidad”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “wrap_content”
android: layout_height = “wrap_content”
android: text = “”
android: id = “@ + id / tv_locality”
android: layout_gravity = “center_vertical”
android: layout_marginLeft = “10dp”
android: textColor = “# 000000”
android: textSize = “20dp” />
android: layout_width = “match_parent”
android: layout_height = “wrap_content”
android: id = “@ + id / btn_start”
android: text = “Obtener ubicación”
android: layout_alignParentBottom = “true” />
MainActivity.java
paquete servicetutorial.service;
importar android. *;
importar android.app.Activity;
importar android.app.ActivityManager;
importar android.content.BroadcastReceiver;
importar android.content.Context;
importar android.content.Intent;
importar android.content.IntentFilter;
importar android.content.SharedPreferences;
importar android.content.pm.PackageManager;
importar android.location.Address;
importar android.location.Geocoder;
importar android.preference.PreferenceManager;
importar android.renderscript.Double2;
importar android.support.v4.app.ActivityCompat;
importar android.support.v4.content.ContextCompat;
importar android.support.v7.app.AppCompatActivity;
importar android.os.Bundle;
importar android.util.Log;
importar android.view.View;
importar android.widget.Button;
importar android.widget.TextView;
importar android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
clase pública MainActivity extiende la actividad {
Botón btn_start;
privado estático final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address, tv_area, tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Doble latitud, longitud;
Geocodificador geocodificador;
@Anular
vacío protegido onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
btn_start = (Botón) findViewById (R.id.btn_start);
tv_address = (TextView) findViewById (R.id.tv_address);
tv_latitude = (TextView) findViewById (R.id.tv_latitude);
tv_longitude = (TextView) findViewById (R.id.tv_longitude);
tv_area = (TextView) findViewById (R.id.tv_area);
tv_locality = (TextView) findViewById (R.id.tv_locality);
geocoder = nuevo Geocoder (this, Locale.getDefault ());
mPref = PreferenceManager.getDefaultSharedPreferences (getApplicationContext ());
medit = mPref.edit ();
btn_start.setOnClickListener (nueva View.OnClickListener () {
@Anular
public void onClick (Ver v) {
if (boolean_permission) {
if (mPref.getString (“servicio”, “”) .matches (“”)) {
medit.putString (“servicio”, “servicio”). commit ();
Intención intención = nueva intención (getApplicationContext (), GoogleService.class);
startService (intento);
} más {
Toast.makeText (getApplicationContext (), “El servicio ya se está ejecutando”, Toast.LENGTH_SHORT) .show ();
}
} más {
Toast.makeText (getApplicationContext (), “Habilite el gps”, Toast.LENGTH_SHORT) .show ();
}
}
});
fn_permission ();
}
privado vacío fn_permission () {
if ((ContextCompat.checkSelfPermission (getApplicationContext (), android.Manifest.permission.ACCESS_FINE_LOCATION)! = PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale (MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} más {
ActivityCompat.requestPermissions (MainActivity.this, new String [] {android.Manifest.permission.ACCESS_FINE_LOCATION
},
SOLICITUD_PERMISIONES);
}
} más {
boolean_permission = true;
}
}
@Anular
public void onRequestPermissionsResult (int requestCode, String [] permissions, int [] grantResults) {
super.onRequestPermissionsResult (requestCode, permissions, grantResults);
switch (requestCode) {
caso REQUEST_PERMISSIONS: {
if (grantResults.length> 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} más {
Toast.makeText (getApplicationContext (), “Por favor permita el permiso”, Toast.LENGTH_LONG) .show ();
}
}
}
}
BroadcastReceiver privado broadcastReceiver = new BroadcastReceiver () {
@Anular
public void onReceive (contexto de contexto, intento de intención) {
latitud = Double.valueOf (intent.getStringExtra (“latutide”));
longitud = Double.valueOf (intent.getStringExtra (“longitud”));
Listar direcciones = nulo;
tratar {
direcciones = geocoder.getFromLocation (latitud, longitud, 1);
Cadena cityName = direcciones.get (0) .getAddressLine (0);
Cadena stateName = direcciones.get (0) .getAddressLine (1);
Cadena countryName = direcciones.get (0) .getAddressLine (2);
tv_area.setText (direcciones.get (0) .getAdminArea ());
tv_locality.setText (stateName);
tv_address.setText (countryName);
} catch (IOException e1) {
e1.printStackTrace ();
}
tv_latitude.setText (latitude + “”);
tv_longitude.setText (longitud + “”);
tv_address.getText ();
}
};
@Anular
nulo protegido en Resume () {
super.onResume ();
registerReceiver (broadcastReceiver, nuevo IntentFilter (GoogleService.str_receiver));
}
@Anular
vacío protegido en pausa () {
super.onPause ();
unregisterReceiver (broadcastReceiver);
}
}
GoogleService.java
paquete servicetutorial.service;
importar android.app.Service;
importar android.content.Context;
importar android.content.Intent;
importar android.location.Location;
importar android.location.LocationListener;
importar android.location.LocationManager;
importar android.os.Bundle;
importar android.os.Handler;
importar android.os.IBinder;
importar android.support.annotation.Nullable;
importar android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
/ **
* Creado por deepshikha el 24/11/16.
* /
GoogleService de clase pública extiende el Servicio implementa LocationListener {
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
doble latitud, longitud;
LocationManager locationManager;
Ubicación ubicación;
manejador privado mHandler = nuevo manejador ();
Temporizador privado mTimer = nulo;
notificar_intervalo largo = 1000;
Cadena estática pública str_receiver = “servicetutorial.service.receiver”;
Intento de intención;
servicio público de Google () {
}
@Nullable
@Anular
public IBinder onBind (Intención de intención) {
volver nulo;
}
@Anular
public void onCreate () {
super.onCreate ();
mTimer = nuevo Timer ();
mTimer.schedule (nuevo TimerTaskToGetLocation (), 5, notify_interval);
intento = nuevo intento (str_receiver);
// fn_getlocation ();
}
@Anular
public void onLocationChanged (ubicación ubicación) {
}
@Anular
public void onStatusChanged (proveedor de cadenas, estado int, paquetes adicionales) {
}
@Anular
public void onProviderEnabled (proveedor de cadenas) {
}
@Anular
public void onProviderDisabled (proveedor de cadenas) {
}
Private void fn_getlocation () {
locationManager = (LocationManager) getApplicationContext (). getSystemService (LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled (LocationManager.NETWORK_PROVIDER);
if (! isGPSEnable &&! isNetworkEnable) {
} más {
if (isNetworkEnable) {
ubicación = nulo;
locationManager.requestLocationUpdates (LocationManager.NETWORK_PROVIDER, 1000,0, esto);
if (locationManager! = null) {
location = locationManager.getLastKnownLocation (LocationManager.NETWORK_PROVIDER);
if (ubicación! = nulo) {
Log.e (“latitud”, location.getLatitude () + “”);
Log.e (“longitud”, location.getLongitude () + “”);
latitude = location.getLatitude ();
longitud = location.getLongitude ();
fn_update (ubicación);
}
}
}
if (isGPSEnable) {
ubicación = nulo;
locationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER, 1000,0, esto);
if (locationManager! = null) {
location = locationManager.getLastKnownLocation (LocationManager.GPS_PROVIDER);
if (ubicación! = nulo) {
Log.e (“latitud”, location.getLatitude () + “”);
Log.e (“longitud”, location.getLongitude () + “”);
latitude = location.getLatitude ();
longitud = location.getLongitude ();
fn_update (ubicación);
}
}
}
}
}
clase privada TimerTaskToGetLocation extiende TimerTask {
@Anular
public void run () {
mHandler.post (nuevo Runnable () {
@Anular
public void run () {
fn_getlocation ();
}
});
}
}
Private void fn_update (Ubicación ubicación) {
intent.putExtra (“latutide”, location.getLatitude () + “”);
intent.putExtra (“longitud”, location.getLongitude () + “”);
sendBroadcast (intento);
}
}
Agregar esta dependencia
compile ‘com.google.android.gms: play-services: 9.4.0’