【问题标题】:onLocationChanged() not calledonLocationChanged() 未调用
【发布时间】:2017-08-09 13:22:05
【问题描述】:

我正在尝试制作一个需要使用 GPS 的应用。所以我写了一个 MainActivity 来启动一个服务。该服务使用 Fused Location Provider 获取位置。所以我的意思是定期获取位置,儿子我使用请求的位置更新。然后我试图通过广播将结果发送到活动。这适用于不需要 onLocationChanged 的​​ getlastlocation()。我了解 onLocationChanged 充当 requesLocationUpdates 回调的侦听器。我一直在谷歌上搜索,但无法得到答案。任何帮助将不胜感激。提前致谢。

这是我的 MainActivity.class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

 //Como queremos recibir datos del servicio locationinfo implementamos   BroadcastReceiver a la clase principal
 public class MainActivity extends AppCompatActivity {

private IntentFilter mIntentFilter;
private TextView mTextView;
public static final String latinfo="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(latinfo);
    mTextView = (TextView) findViewById(R.id.texto);
    //Iniciamos el servicio locationinfo. Para ello creamos una petición (intent)

    Intent serviceIntent = new Intent(this, locationinfo.class);
    startService(serviceIntent);
    //Registramos el recibidor del servicio.
    //registerReceiver(mReceiver, mIntentFilter);
}

@Override
public void onResume() {
    super.onResume();
    registerReceiver(mReceiver, mIntentFilter);
}

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        mTextView.setText(mTextView.getText()+ "Respuesta del GPS \n");
        if (intent.getAction().equals(latinfo)) {
            mTextView.setText(mTextView.getText()
                    + intent.getStringExtra("longitud") + "\n\n");

        }
        else {

            Toast.makeText(context,"No se recibe nada",Toast.LENGTH_LONG).show();
            Intent stopIntent = new Intent(MainActivity.this,
                    locationinfo.class);
            stopService(stopIntent);
        }

        }


};

}

这就是 service.class

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
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;




 //Servicio de localizacion mediante FusedLocationProvider

 public class locationinfo extends Service implements    GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
   //Definimos las variables que vamos a utilizar
   GoogleApiClient miGoogleApi;
Double longitud; // declaramos el valor de longitud
Double latitud; // declaramos el valor de latitud
String infolongi; //Si queremos utilizar el texto para mostrarlo de la longitud, lo haremos como string. Por tanto lo declaramos
String infolati; //Si queremos utilizar el texto para mostrarlo de la latitud, lo haremos como string. Por tanto lo declaramos
Location  localizacion; //el objeto localizacion que tendrá toda la geo-informacion
//int causafallo;
private static final String TAG = "LocationActivity";



//Creamos el servicio y creamos tambien el objeto/cliente que se conectará con los servicios de Google.
//Para ello utilizamos un constructor (Builder) que engloba varios métodos. Entre ellos los métodos addConnectionCallbacks y
//addOnConnectionFailedListener. Estos métodos exigen ser implementados en la clase y necesitan de 2 métodos heredados que
//se tienen que declarar en el código. addOnConnectionFailedListener exige la declaración de onConnectionFailed(ConnectionResult algo)
//y addConnectionCallback exige la declaración de onConnectionSuspended(int).

public void onCreate(){

    miGoogleApi=new GoogleApiClient.Builder(this)
     .addConnectionCallbacks(this)
     .addOnConnectionFailedListener(this)
     .addApi(LocationServices.API)
     .build();

    //Una vez creado el objeto lo conectamos con los servicios de Google (Esta conexión se debe hacer en el método
    //onResume() en caso de tratarse de una Activity al igual que la desconexión se debe hacer con 'objeto.disconnect()
    // en el método onPause()

    miGoogleApi.connect();
}

//Una vez que está conectado. Necesario por le metodo ConnectionCallBAck()
@Override
public void onConnected(Bundle melasuda) {



    //Llenamos el objeto 'localizacion' con la informacion solicitada al proveedor FusedLocationServices
    //En este caso pedimos la última posición conocida mediante el método getLastLocation() al que se le dice que
    // utilice el objeto/cliente que hemos creado


    //localizacion = LocationServices.FusedLocationApi.getLastLocation(miGoogleApi);

    //Creamos el objeto LocationRequest que tendrá varios parametros

    LocationRequest mlocationrequest=new LocationRequest();
    mlocationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mlocationrequest.setInterval(5000); // Actualizamos cada 5 segundos
    mlocationrequest.setFastestInterval(3000); //El caso más rápido de actualizacion
    mlocationrequest.setSmallestDisplacement(10); //Distancia para hacer actualizaion

    //Ahora en vez de obterner la última localización, vamos a pedir  que actualice la posición cada cierto tiempo. Para ello vamos a llamar
    //a una función que vamos a crear. Esta llamada debe de hacerse desde aquí, desde onConnected()


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(getBaseContext(), "Permisos de uso de GPS activados", Toast.LENGTH_LONG).show();
        //localizacion = LocationServices.FusedLocationApi.getLastLocation(miGoogleApi);
        LocationServices.FusedLocationApi.requestLocationUpdates(miGoogleApi, mlocationrequest, this);
    }

}


//Este método funciona como el Listener de requestLocationUpdates
@Override
public void onLocationChanged(Location location){
    localizacion = location;
    Toast.makeText(getBaseContext(),"estamos en onlocationchanged",Toast.LENGTH_LONG).show();
    updateUI();

}

private void updateUI() {
    infolati=String.valueOf(localizacion.getLatitude());
    infolongi=String.valueOf(localizacion.getLongitude());

    new Thread(new Runnable() {
        public void run() {
            if (localizacion != null) {
                //Le pasamos el objeto con la informacion a una funcion que vamos a crear para que obtenga lo que queramos
                longitud=localizacion.getLongitude();
                latitud=localizacion.getLatitude();
                infolongi=String.valueOf(longitud);
                infolati=String.valueOf(latitud);


            } else {
                infolongi="El valor de localizacion devuelve nulo";

            }

            //Le damos 5 segundos para que puede conectar con la señal GPS
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //Enviamos los datos para que puedan ser recogidos por la aplicación
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(MainActivity.latinfo);
            broadcastIntent.putExtra("longitud",infolongi);
            broadcastIntent.putExtra("latitud",infolati);
            sendBroadcast(broadcastIntent);

        }
    }).start();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i("MyService", "Received start id " + startId + ": " + intent);
    return START_STICKY; // run until explicitly stopped.
}
//Se llama desde la aplicación  con startService(Intent). Asigna un codigo al servicio




//Método necesario para addConnectionCallback(). Devuelve un entero con la causa de fallo
public void onConnectionSuspended(int causafallo){

}
//Método necesario para addOnConnectionFailedListener(). Devuelve un código que puede ser del tipo boolean,string, int,
//o pendingintent del probela encontrado si falla la conexión. Lo hace utilizando la clase ConnectionResult
public void onConnectionFailed(ConnectionResult result){
    Toast.makeText(getBaseContext(),"Ha fallado la conexion:"+result.getErrorCode(),Toast.LENGTH_LONG).show();
//Y hacemos un log por si tenemos que hace un debug

    Log.i(TAG,"onConnectionFailed:"+result.getErrorCode()+","+result.getErrorMessage());
}

//Función que apaga el servicio
@Override
public void onDestroy() {
    // Cancel the persistent notification.


    // Tell the user we stopped.
    Toast.makeText(this, "Se ha parado el servicio de localizacion", Toast.LENGTH_SHORT).show();
}

//Lanza el servicio
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Todavía no implementado");
}
}

【问题讨论】:

  • 显然您的 requestlocationupdates() 没有被调用。您在哪个 API 版本上测试应用程序?如果是 23 岁及以上,则需要以编程方式请求权限。
  • 我正在使用 API 23。但我认为使用此代码 "if ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {..." 就在 requestLocationUpdates 之前,我正在以编程方式请求许可。事实上,如果我更改为 getLastLocation 它就可以了。

标签: java android android-fusedlocation


【解决方案1】:

这对我有用:https://stackoverrun.com/es/q/2346171

我曾与:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);                   
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

【讨论】:

【解决方案2】:

好的,我找到了解决方案。 OnLocationChanged 仅在“更改位置”之后调用,这意味着需要先获取要比较的位置。这是getLastLocation()获得的。

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 2019-02-07
    • 2023-03-13
    • 2015-09-28
    • 2014-11-23
    • 2017-08-27
    • 2012-08-09
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多