位置永远为空

普拉纳夫·in那(Pranav Jain)

这是我的android项目。该应用程序显示有关当前位置的信息。
但是,该应用程序始终显示该位置为空。我已经搜索了很多,但是仍然找不到解决方案或无法实施该解决方案。

这是我的MainActivity代码,

package com.learning.pranavjain.hikerswatch;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.IOException; 
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity implements LocationListener {

LocationManager locationManager;
String provider;
String sLatitude;
String sLongitude;
String sAccuracy;
String sSpeed;
String sAltitude;
TextView addressTV;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Hiding the status bar
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(),false);

    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;
    }
    locationManager.requestLocationUpdates(provider,400,1,this);
    location = locationManager.getLastKnownLocation(provider);

    if(location==null){
        Log.i("Location1","NULL1");
        Toast.makeText(this,"Location not found",Toast.LENGTH_SHORT).show();
    }

    if(location!=null) {
        onLocationChanged(location);
        Log.i("Location1","Reached here");
    }

}

@Override
protected void onResume() {
    super.onResume();


    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;
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

@Override
public void onLocationChanged(Location location) {



    Double lat = location.getLatitude();
    Double lng = location.getLongitude();
    Float acc = location.getAccuracy();
    Float spe = location.getSpeed();
    Double alt = location.getAltitude();

    Log.i("Location","reached here");

    TextView latitude = (TextView) findViewById(R.id.latitude);
    TextView longitude = (TextView) findViewById(R.id.longitude);
    TextView accuracy = (TextView) findViewById(R.id.accuracy);
    TextView speed = (TextView) findViewById(R.id.speed);
    TextView altitude = (TextView) findViewById(R.id.altitude);
    addressTV = (TextView) findViewById(R.id.address);

    sLatitude = latitude.getText().toString();
    sLongitude = longitude.getText().toString();
    sAccuracy = accuracy.getText().toString();
    sSpeed = speed.getText().toString();
    sAltitude = altitude.getText().toString();

    sLatitude += Double.toString(lat);
    sLongitude += Double.toString(lng);
    sAccuracy += Double.toString(acc);
    sSpeed += Double.toString(spe);
    sAltitude += Double.toString(alt);

    latitude.setText(sLatitude);
    longitude.setText(sLongitude);
    accuracy.setText(sAccuracy);
    speed.setText(sSpeed);
    altitude.setText(sAltitude);

    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

    try {
        List<Address> listAddresses = geocoder.getFromLocation(lat, lng, 1);

        if (listAddresses != null && listAddresses.size() > 0 ) {

            Log.i("PlaceInfo", listAddresses.get(0).toString());

            String addressHolder = "";

            for (int i = 0; i <= listAddresses.get(0).getMaxAddressLineIndex(); i++) {

                addressHolder += listAddresses.get(0).getAddressLine(i) + "\n";

            }

            addressTV.setText("Address:\n" + addressHolder);

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.i("Location:", String.valueOf(lat));
    Log.i("Location:", lng.toString());

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
protected void onPause() {
    super.onPause();

    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;
    }
    locationManager.removeUpdates(this);

 }
}

这是我的清单代码,

<?xml version="1.0" encoding="utf-8"?>

<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" />
<uses-feature android:name="android.hardware.location.network" />
<uses-feature android:name="android.hardware.location.gps" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

整个项目可以在这里找到(GitHub)

萨文

嗨,为什么要尝试使用getLastKnownLocation。它会返回您以前的经度和纬度,并且可能需要一些时间来更新lastknown location很有可能它会在您所在的位置后重新运行以使您返回null。

我只是在指您google Fused api来定位任何更新或最新的位置。它非常准确。

如何在您的项目中融合api。

步骤1.使此类成为GoogleLocationService.java

public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;


public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
    this.locationUpdateListener = locationUpdateListener;
    this.activity = activity;
    buildGoogleApiClient();
}

protected synchronized void buildGoogleApiClient() {
    //Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(activity)
            .addConnectionCallbacks(callbacks)
            .addOnConnectionFailedListener(callbacks)
            .addApi(LocationServices.API)
            .build();
    createLocationRequest();
    mGoogleApiClient.connect();
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

}

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
            Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();

        }
        locationUpdateListener.cannotReceiveLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location.hasAccuracy()) {
            if (location.getAccuracy() < 30) {
                locationUpdateListener.updateLocation(location);
            }
        }
    }
}

private static boolean locationEnabled(Context context) {
    boolean gps_enabled = false;
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return gps_enabled;
}

private boolean servicesConnected(Context context) {
    return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}

private boolean isPackageInstalled(String packagename, Context context) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}


public void startUpdates() {
    /*
     * Connect the client. Don't re-start any requests here; instead, wait
     * for onResume()
     */
    if (servicesConnected(activity)) {
        if (locationEnabled(activity)) {
            locationUpdateListener.canReceiveLocationUpdates();
            startLocationUpdates();
        } else {
            locationUpdateListener.cannotReceiveLocationUpdates();
            Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
        }
    } else {
        locationUpdateListener.cannotReceiveLocationUpdates();
        Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
    }
}

//stop location updates
public void stopUpdates() {
    stopLocationUpdates();
}

//start location updates
private void startLocationUpdates() {

    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
    }
}

public void stopLocationUpdates() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
    }
}

public void startGoogleApi() {
    mGoogleApiClient.connect();
}

public void closeGoogleApi() {
    mGoogleApiClient.disconnect();
}

 }

第2步。将此接口设置为LocationUpdateListener.java

 public interface LocationUpdateListener {

/**
 * Called immediately the service starts if the service can obtain location
 */
void canReceiveLocationUpdates();

/**
 * Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
 */
void cannotReceiveLocationUpdates();

/**
 * Called whenever the location has changed (at least non-trivially)
 * @param location
 */
void updateLocation(Location location);

/**
 * Called when GoogleLocationServices detects that the device has moved to a new location.
 * @param localityName The name of the locality (somewhere below street but above area).
 */
void updateLocationName(String localityName, Location location);
}

第3步。在您要获取位置的位置使用这段代码

public class MainActivity extends ActionBarActivity {

private GoogleLocationService googleLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
    @Override
    public void canReceiveLocationUpdates() {
    }

    @Override
    public void cannotReceiveLocationUpdates() {
    }

    //update location to our servers for tracking purpose
    @Override
    public void updateLocation(Location location) {
        if (location != null ) {
            Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());

        }
    }

    @Override
    public void updateLocationName(String localityName, Location location) {

        googleLocationService.stopLocationUpdates();
    }
});
googleLocationService.startUpdates();


}

@Override
public void onDestroy() {
    super.onDestroy();
if (googleLocationService != null) {
    googleLocationService.stopLocationUpdates();
}

}
}

希望这会帮助你。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

永远为假的Q对象

来自分类Dev

迅捷:检测bodyAtPoint。永远为零

来自分类Dev

永远为Node.js清空输出

来自分类Dev

永远为背景的node.js参数

来自分类Dev

永远为无法在ubuntu服务器中工作的nodeJs服务

来自分类Dev

的IntelliJ秀“总是为真”的提示,但不是“永远为假”的的instanceof

来自分类Dev

onLocationChanged(位置位置)永远不会被调用

来自分类Dev

为什么光标永远不会为空?

来自分类Dev

屈服的ienumerable永远可以为空吗?

来自分类Dev

C / C ++链表永远不会为空

来自分类Dev

使用屏幕上的随机位置永远移动精灵

来自分类Dev

GET请求中的Dto永远不会显示为空

来自分类Dev

文本框永远不能为空。C#

来自分类Dev

数组永远不会为空,但打字稿不知道

来自分类Dev

永远不应为空的 C# 变量引发空引用异常

来自分类Dev

频率和位置,使空 - 检查

来自分类Dev

Facebook位置显示为空

来自分类Dev

std :: list是否保证项目永远不会移动到其他内存位置?

来自分类Dev

永远在后台运行Swift 2.0应用程序以更新服务器位置

来自分类Dev

等待一个空任务永远旋转(等待新Task(()=> {}))

来自分类Dev

Libgdx Scene2d进度栏永远不会为空

来自分类Dev

C#定义一个类实例永远不能为空(它不包含任何数据)

来自分类Dev

当我使用plone.api content.create中的查找结果时永远是空的

来自分类Dev

[FromBody] 会不会总是将我从永远不会为空的参数中拯救出来?

来自分类Dev

空元素的位置与有内容的元素的位置不同吗?

来自分类Dev

位置管理器提供空坐标

来自分类Dev

为什么ReferencedSymbol的位置为空?

来自分类Dev

检查数组位置是否为空

来自分类Dev

如何设置,如果位置空OOP

Related 相关文章

热门标签

归档