GPS提供商未被触发 - 谷歌播放服务位置api?

时间:2014-04-10 04:41:46

标签: android google-maps location google-play-services

我正在使用google play services api来获取位置 但我注意到他们根本没有触发GPS提供商 当你在户外时谷歌地图会自动触发GPS

public class MainActivity extends Activity implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener, LocationListener,
    com.google.android.gms.location.LocationListener {



private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
FragmentManager myFragmentManager;
static MapFragment myMapFragment;
public static GoogleMap myMap;
LocationClient mLocationClient;



// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND
        * UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND
        * FASTEST_INTERVAL_IN_SECONDS;
private static final String TAG = "CheckCurLocation";

// Define an object that holds accuracy and frequency parameters
LocationRequest mLocationRequest;
boolean mUpdatesRequested;

SharedPreferences mPrefs;
SharedPreferences.Editor mEditor;
Location myCurrentLocation;
Button mLocBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLocBtn = (Button) findViewById(R.id.locationBtn);
    mPrefs = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
    // Get a SharedPreferences editor
    mEditor = mPrefs.edit();
    mLocationClient = new LocationClient(MainActivity.this, this, this);
    mUpdatesRequested = false;
    mLocationRequest = LocationRequest.create();
    // Use high accuracy


    myFragmentManager = getFragmentManager();
    myMapFragment = (MapFragment) myFragmentManager
            .findFragmentById(R.id.map);
/*  startActivity(new Intent(
            Settings.ACTION_LOCATION_SOURCE_SETTINGS));*/



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onPause() {
    mEditor.putBoolean("KEY_UPDATES_ON", mUpdatesRequested);
    mEditor.commit();
    super.onPause();
}

public void getLoction(View v) {
    if (mLocationClient.isConnected()) {

        Log.d(TAG, "Location client connected");
        Location currentLocation = mLocationClient.getLastLocation();
        Toast.makeText(MainActivity.this, "client connected",
                Toast.LENGTH_LONG).show();
        if (currentLocation != null) {

            Log.d(TAG, "Location client connected");
            Log.d(TAG, "Lasloc === " + currentLocation);
            drawMap(currentLocation);

        } else {
            MainActivity.this.startActivity(new Intent(
                    Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            Log.d(TAG, "location null");
            Toast.makeText(MainActivity.this, "  location null",
                    Toast.LENGTH_LONG).show();
        }

    } else if (mLocationClient.isConnecting()) {

        Log.d(TAG, "client connecting");
        Toast.makeText(MainActivity.this, "client connecting",
                Toast.LENGTH_LONG).show();

    } else {

        Log.d(TAG, "client not connected");
        Toast.makeText(MainActivity.this, "client not connected",
                Toast.LENGTH_LONG).show();

    }
}

@Override
protected void onResume() {
    super.onResume();
    /*
     * Get any previous setting for location updates Gets "false" if an
     * error occurs
     */
    if (mPrefs.contains("KEY_UPDATES_ON")) {
        mUpdatesRequested = mPrefs.getBoolean("KEY_UPDATES_ON", false);

        // Otherwise, turn off location updates
    } else {
        mEditor.putBoolean("KEY_UPDATES_ON", false);
        mEditor.commit();
    }
    /*
     * Location currentLocation = mLocationClient.getLastLocation();
     * drawMap(mLocationClient.getLastLocation()); }
     */
}

private void drawMap(Location lastLocation) {
    myMap = myMapFragment.getMap();

    if (myMap != null) {
        final LatLng HAMBURG = new LatLng(lastLocation.getLatitude(),
                lastLocation.getLongitude());
        Toast.makeText(MainActivity.this, "update google play services"+lastLocation.getLatitude()+","+lastLocation.getLongitude(),
                Toast.LENGTH_LONG).show();
myMap.clear();
        myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        myMap.getUiSettings().setZoomControlsEnabled(true);
        myMap.getUiSettings().setCompassEnabled(true);
        myMap.getUiSettings().setAllGesturesEnabled(true);
        myMap.getUiSettings().setMyLocationButtonEnabled(true);
        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        myMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(HAMBURG, 14, 0, 90)));
        myMap.addMarker(new MarkerOptions().position(HAMBURG)
        .title("I am here"+lastLocation.getLatitude()+","+lastLocation.getLongitude()).flat(true).rotation(245));

    } else if (GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(getApplicationContext()) != ConnectionResult.SUCCESS) {
        Toast.makeText(MainActivity.this, "update google play services",
                Toast.LENGTH_LONG).show();
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    /*
     * Google Play services can resolve some errors it detects. If the error
     * has a resolution, try sending an Intent to start a Google Play
     * services activity that can resolve error.
     */
    if (result.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            result.startResolutionForResult(this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {

        Toast.makeText(MainActivity.this, "update services",
                Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onStart() {

    super.onStart();
    mLocationClient.connect();

}

@Override
protected void onStop() {

    super.onStop();
    mLocationClient.disconnect();
}

@Override
public void onConnected(Bundle connectionHint) {
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();

    // If already requested, start periodic updates


        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        // Set the fastest update interval to 1 second
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        mLocationClient.requestLocationUpdates(mLocationRequest, this);


    Log.d(TAG, "Location client Connected =========");
}

@Override
public void onDisconnected() {
    Toast.makeText(this, "Dis Connected", Toast.LENGTH_SHORT).show();
    if (mLocationClient.isConnected()) {
        /*
         * Remove location updates for a listener. The current Activity is
         * the listener, so the argument is "this".
         */

        mLocationClient.removeLocationUpdates(this);
        // removeLocationUpdates(this);
    }
    /*
     * After disconnect() is called, the client is considered "dead".
     */
    mLocationClient.disconnect();
    Log.d(TAG, "Location client disconnected =========");
    super.onStop();
}

@Override
public void onLocationChanged(Location location) {
    String msg = "Updated Location: "
            + Double.toString(location.getLatitude()) + ","
            + Double.toString(location.getLongitude());
    Log.d(TAG, "Onlocation changed" + msg);

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

}

清单

<permission
    android:name="com.example.checkmaps.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    

启用手机中所有基于位置的设置

问题iam无法在室外环境中获得任何基于GPS的定期更新,因为谷歌地图获得了基于GPS的定期更新 我在位置请求设置中遗漏了一些东西

1 个答案:

答案 0 :(得分:0)

您没有获得GPS更新的可能性是:

1)尝试在应用程序清单文件中添加另一个权限:

  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2)顺便提一下你的<meta-data>代码:

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

              <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="YourApiKey" />

3)只能从Android或google-play-service库中使用一个 LocationListener ,不确定是否可能会发生冲突。如果您使用的是 LocationClient ,则在您想要进行位置更新之前,请不要断开连接。

4)您应该在 * drawMap () *函数中添加以下代码行:

myMap.setMyLocationEnabled(true);