Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法获取位置-Android_Android - Fatal编程技术网

无法获取位置-Android

无法获取位置-Android,android,Android,我想在安卓2.2中获得位置,我已经添加了谷歌gms播放服务库。我可以设置requestLocationUpdates和getlastnownlocation,但位置为空 日志仅打印03-10 01:23:13.720 27437-27437/?V/GPSTracker提供程序﹕ 全球定位系统 03-10 01:23:13.720 27437-27437/? V/GPSTracker﹕ 请求位置更新 03-10 01:23:13.720 27437-27437/? V/GPSTracker﹕

我想在安卓2.2中获得位置,我已经添加了谷歌gms播放服务库。我可以设置
requestLocationUpdates
getlastnownlocation
,但位置为空

日志仅打印
03-10 01:23:13.720 27437-27437/?V/GPSTracker提供程序﹕ 全球定位系统
03-10 01:23:13.720  27437-27437/? V/GPSTracker﹕ 请求位置更新
03-10 01:23:13.720  27437-27437/? V/GPSTracker﹕ getLastKnownLocation
。纬度和经度没有显示出来

package com.example.testlocation;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private Context mContext;
    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    String provider = "";
    float accuracy = 0;

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker() {

    }

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                Criteria criteria = new Criteria();
                provider = locationManager.getBestProvider(criteria, true);
                if (provider != null) {
                    locationManager.requestLocationUpdates(provider,30000,10, this);
                    Log.v("GPSTracker", "requestLocationUpdates");
                }
                if (locationManager != null && provider != null) {
                    location = locationManager.getLastKnownLocation(provider);
                    Log.v("GPSTracker", "getLastKnownLocation");
                    if (location != null) {
                        accuracy = location.getAccuracy();
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        Log.v("GPSTracker", latitude+", "+longitude);
                    }
                }

            }

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

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
        getLatitude();
        getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public String getProvider(){
        return provider;
    }

    public float getAccuracy (){
        return accuracy;
    }

}
MainActivity.java

public class MainActivity extends ActionBarActivity {

    private TextView tvLat, tvLong, tvProvider, tvAccuracy;
    private Button btnRefresh;
    private double latitude, longitude;
    private GPSTracker gps;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvProvider = (TextView)findViewById(R.id.tvProvider);
        tvAccuracy = (TextView)findViewById(R.id.tvAccuracy);
        tvLat = (TextView)findViewById(R.id.tvLat);
        tvLong = (TextView)findViewById(R.id.tvLong);
        btnRefresh = (Button)findViewById(R.id.btnRefresh);

        gps = new GPSTracker(this);
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        tvProvider.setText("Provider: "+gps.getProvider());
        tvAccuracy.setText("Accuracy: "+gps.getAccuracy());
        tvLat.setText("Latitude: "+latitude);
        tvLong.setText("Longitude: "+longitude);

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                tvProvider.setText("Provider: "+gps.getProvider());
                tvAccuracy.setText("Accuracy: "+gps.getAccuracy());
                tvLat.setText("Latitude: "+latitude);
                tvLong.setText("Longitude: "+longitude);
            }
        });
    }

}
Gradle

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:6.5.87'
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.testlocation" >
    <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"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <uses-sdk tools:overrideLibrary="com.google.android.gms"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service android:name=".GPSTracker" />
    </application>

</manifest>
清单文件

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:6.5.87'
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.testlocation" >
    <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"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <uses-sdk tools:overrideLibrary="com.google.android.gms"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service android:name=".GPSTracker" />
    </application>

</manifest>

您正在设置位置并立即获取位置!这没有足够的时间来获取位置,因此您将得到null。您应该实现locationlistener,并在其中(onLocationChanged方法)获取并显示位置

你把你的GPS代码放在服务中,而你实际上没有服务的其他代码,你甚至没有启动它。我认为你是android新手,你已经在尝试高级领域了。这是我给你的建议

而不是

public class GPSTracker extends Service implements LocationListener {

同样在GPSTracker中,执行以下操作 公共void init(){ 试一试{ locationManager=(locationManager)mContext .getSystemService(位置服务)

在MainActivity.java中,在实例化后执行gps.init()。运行它,查看它是否运行,并观察输出是否有错误


另外,不要忘记从xml中删除该服务,但是我已经设置了onLocationChanged、public void onLocationChanged(Location-Location){this.Location=Location;},并将MainActivity上的一个按钮设置为刷新,但仍然无法获取位置。那么,您应该将其放在上面的代码中,以便我们可以看到它!…是否调用了您的OnLocationChanged?放置断点或语句另外,您是否可以放置一个print语句以查看您从“getBestProvider”获得的提供程序?首先要做的是查看您是否在onlocationchanged中找到了代码。输入断点或日志语句。同时打印/记录您获得的提供商的名称。这将有助于了解问题所在。我的期望是您没有获得位置更新,或者条件返回空提供商。我建议,r将此locationManager.RequestLocationUpdate(提供程序,30000,10,此)替换为locationManager.RequestLocationUpdate(提供程序,3000,0,此);然后试一试。好的,我得问一下……你是否正确地测试了你的应用程序?你是否移动了至少10米并等待了3秒钟?然后你的
onLocationChanged
应该已经启动,如果你在其中记录了什么,它应该已经打印出来了……方法
getLastKnownLocation
可以返回
null
,这就是comp完全正常,但你的
onLocationChanged
应该在移动10米和3秒后发射,并且应该有新的坐标…我至少等待了10分钟以上,纬度和经度仍然为0。你在等待时移动了10米吗?你需要移动并等待时间过去(根据文档:“minDistance参数还可用于控制位置更新的频率。如果该参数大于0,则位置提供程序将仅在位置更改至少minDistance米且至少超过minTime毫秒时向您的应用程序发送更新。”)