【问题标题】:android current location GPS but return nullandroid当前位置GPS但返回null
【发布时间】:2012-10-14 15:18:38
【问题描述】:

我开发了一个应用程序来通过 GPS 检索当前位置,但它返回 null 我希望我的应用程序只使用 gps,而不是 3g 或 wifi 我使用 bestprovider 但它仅在我运行时检索,并不总是有效

这是java代码:

    package com.example.loc2;

    import android.location.Location;
 import android.location.LocationListener;
   import android.location.LocationManager;
  import android.os.Bundle;
   import android.app.Activity;
   import android.content.Context;
   import android.view.Menu;
    import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
   import android.widget.Toast;

   public class MainActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters  
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

retrieveLocationButton.setOnClickListener(new OnClickListener() {
       // @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
});        

}    

protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: "+location.getLongitude()+" \n Latitude:"+
                 location.getLatitude());

        Toast.makeText(  MainActivity.this,message,
                Toast.LENGTH_LONG).show();
    }

}   

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}

这是清单: 我使用了这个权限

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loc2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<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_MOCK_LOCATION"/>

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

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

    </manifest>

请帮忙

【问题讨论】:

    标签: android get gps location


    【解决方案1】:

    步骤 1> 准备 GoogleClientAPI 实例
    step 2> 在 onConnected 回调中使用 andorid 运行时权限机制在运行时检查位置预授权

    步骤 3> 获取位置 Location location1 = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    步骤 4> 将位置请求准备为 LocationRequest locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(0) .setFastestInterval(0);

    setp 5> 注册位置更新为

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);

    步骤 6> 从布局中获取 MapFragment 实例

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); supportMapFragment.getMapAsync(this);

    【讨论】:

      【解决方案2】:

      你必须有正确的调用方法的顺序/顺序。

      onCreate() {   
          GoogleApiAvailability mGoogleApiAvailability = GoogleApiAvailability.getInstance();   
      
          byte b = (byte) mGoogleApiAvailability.isGooglePlayServicesAvailable(this);    
      
      
          if (b == ConnectionResult.SUCCESS) {    
              try {   
                  MapsInitializer.initialize(getApplicationContext());    
      
                  //setUpMap();    
      
                  if (mGoogleApiClient == null) {    
                      mGoogleApiClient = new GoogleApiClient.Builder(this)
                              .addApi(LocationServices.API)
                              .addConnectionCallbacks(this)
                              .addOnConnectionFailedListener(this)
                              .build();   
                  }    
              }catch(Exception e) {    
                  e.printStackTrace();   
              }   
          }   
      }   
      
      @Override   
      public void onConnected(@Nullable Bundle bundle) {       
          checkForLocationPermission();      
      
          Location location1 = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);    
      
          if(location1 != null) {       
              currentLatitude = location1.getLatitude();    
              currentLongitude = location1.getLongitude();    
          }    
      
          startLocationUpdtes();    
          setUpMap();    
      
      }    
      
      
      @Override    
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {    
      //super.onRequestPermissionsResult(requestCode, permissions, grantResults);    
      
          switch(requestCode) {    
              case MY_LAST_KNOWN_LOCATION_PERMISSION:    
                  if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {    
      
                      //Permission was allowed    
                      isLocationAccessAllowed = true;    
                  } else {    
                      //Permission was denied      
                  }     
          }     
      }    
      
      @Override    
      public void onConnectionSuspended(int i) {    
      
      }    
      
      @Override    
      public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {    
      
      }    
      
      @Override    
      public void onLocationChanged(Location location) {    
      
          currentLatitude = location.getLatitude();    
      
          currentLongitude = location.getLongitude();    
      
      }     
      
      private void checkForLocationPermission() {    
          boolean isFineLocationNotAllowed = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED;    
      
          boolean isCoarseLocationNotAllowed = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;    
      
          if(isFineLocationNotAllowed && isCoarseLocationNotAllowed) {    
      
              //Permission is not granted yet    
              boolean shouldRequestForPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION);     
      
              if(shouldRequestForPermission) {    
                  //user has allowed permission    
      
                  ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION}, MY_LAST_KNOWN_LOCATION_PERMISSION);   
      
              } else {    
                  //user has denied permission    
              }    
      
          } else {    
              //permission is already granted    
      
              //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION}, MY_LAST_KNOWN_LOCATION_PERMISSION);    
          }    
      }    
      

      【讨论】:

      • 首先使用 GoogleClientAPi 设置 api,然后在 OnConnected 回调中检查运行时 Loa=cation 权限,然后准备位置请求
      【解决方案3】:

      看看这个,对你有帮助

       LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
          LocationListener mlocListener = new MyLocationListener();
      mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                  mlocListener);
      
      public class MyLocationListener implements LocationListener {
      
          @Override
          public void onLocationChanged(Location loc) {
              loc.getLatitude();
              loc.getLongitude();
      
              Geocoder gcd = new Geocoder(getApplicationContext(),
                      Locale.getDefault());
              try {
                  mAddresses = gcd.getFromLocation(loc.getLatitude(),
                          loc.getLongitude(), 1);
      
              } catch (IOException e) {
      
              }
      
              String cityName = (mAddresses != null) ? mAddresses.get(0)
                      .getLocality() : TimeZone.getDefault().getID();
              String countryName = (mAddresses != null) ? mAddresses.get(0)
                      .getCountryName() : Locale.getDefault().getDisplayCountry()
                      .toString();
      
      
              mCurrentSpeed.setText("Longitude"+loc.getLongitude()+" Latitude"+loc.getLatitude());
          }
      
          @Override
          public void onProviderDisabled(String provider) {
              Toast.makeText(getApplicationContext(), "Gps Disabled",
                      Toast.LENGTH_SHORT).show();
          }
      
          @Override
          public void onProviderEnabled(String provider) {
              Toast.makeText(getApplicationContext(), "Gps Enabled",
                      Toast.LENGTH_SHORT).show();
          }
      
          @Override
          public void onStatusChanged(String provider, int status, Bundle extras) {
          }
      }
      

      【讨论】:

      • 谢谢你,但是 mAddresses 是什么类型的,因为它不起作用
      • mAddresses 属于地址类型
      • 请注意:我在使用内置 GeoCoder 服务时遇到了很多问题,因为它喜欢随机禁用自身。重新启动设备将解决 GeoCoder 问题,但更好的方法是向 Google 的网络 GeoCoder 服务发送网络请求,因为我从未见过失败。
      猜你喜欢
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多