getLastLocation谷歌服务

时间:2015-12-29 06:29:36

标签: java android

我开发了一个应用程序来获取当前位置但是我没有得到任何位置,我也尝试了GoogleService failed to initialize中的解决方案,但它对我没用。

这是我的主要活动:

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.location.LocationServices;

public class GetLocation extends AppCompatActivity implements     GoogleApiClient.ConnectionCallbacks,     GoogleApiClient.OnConnectionFailedListener {

public GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_location);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

//        mGoogleApiClient = new GoogleApiClient.Builder(this)
//                .addApi(Drive.API)
//                .addScope(Drive.SCOPE_FILE)
//                .build();

    // Create an instance of GoogleAPIClient.
    //if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
   // }

}


protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_get_location, menu);
    return true;
}

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



@Override
public void onConnected(Bundle connectionHint) {
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
        TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }

}

@Override
public void onConnectionSuspended(int i) {
    TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
    TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
    mLatitudeText.setText("onConnectionSuspended");
    mLongitudeText.setText("onConnectionSuspended");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
    TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
    mLatitudeText.setText(String.valueOf(connectionResult));
    mLongitudeText.setText("onConnectionFailed");

    }
   }

这是我的Logcat

12-29 01:16:41.170 14919-14919/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
12-29 01:16:41.170 14919-14919/? D/AndroidRuntime: CheckJNI is ON
12-29 01:16:41.200 14919-14919/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
12-29 01:16:41.230 14919-14919/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-29 01:16:41.230 14919-14919/? E/android.os.Debug: failed to load memtrack module: -2
12-29 01:16:41.240 14919-14919/? I/Radio-JNI: register_android_hardware_Radio DONE
12-29 01:16:41.250 14919-14919/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
12-29 01:16:41.250 1358-1791/system_process I/ActivityManager: Force stopping com.timesavii.getlocation appid=10043 user=0: from pid 14919
12-29 01:16:41.250 1358-1791/system_process I/ActivityManager: Killing 14857:com.timesavii.getlocation/u0a43 (adj 0): stop com.timesavii.getlocation
12-29 01:16:41.280 1358-1394/system_process W/InputDispatcher: channel '683d475 com.timesavii.getlocation/com.timesavii.getlocation.GetLocation (server)' ~ Consumer closed input channel or an error occurred.  events=0x9
12-29 01:16:41.280 1358-1394/system_process E/InputDispatcher: channel '683d475 com.timesavii.getlocation/com.timesavii.getlocation.GetLocation (server)' ~ Channel is unrecoverably broken and will be disposed!
12-29 01:16:41.280 1358-1596/system_process D/GraphicsStats: Buffer count: 2
12-29 01:16:41.280 1358-1596/system_process I/WindowState: WIN DEATH: Window{683d475 u0 com.timesavii.getlocation/com.timesavii.getlocation.GetLocation}
12-29 01:16:41.280 1358-1596/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel '683d475 com.timesavii.getlocation/com.timesavii.getlocation.GetLocation (server)'
12-29 01:16:41.300 1358-1791/system_process W/ActivityManager: Force removing ActivityRecord{afb69f2 u0 com.timesavii.getlocation/.GetLocation t91}: app died, no saved state
12-29 01:16:41.310 14919-14919/? D/AndroidRuntime: Shutting down VM
12-29 01:16:41.320 1358-1789/system_process W/ActivityManager: Spurious death for ProcessRecord{9193003 0:com.timesavii.getlocation/u0a43}, curProc for 14857: null
12-29 01:16:41.390 1688-1978/com.google.android.googlequicksearchbox W/EGL_emulation: eglSurfaceAttrib not implemented
12-29 01:16:41.390 1688-1978/com.google.android.googlequicksearchbox W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe12b8480, error=EGL_SUCCESS
12-29 01:16:42.200 14928-14928/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
12-29 01:16:42.200 14928-14928/? D/AndroidRuntime: CheckJNI is ON
12-29 01:16:42.210 14932-14932/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
12-29 01:16:42.210 14932-14932/? D/AndroidRuntime: CheckJNI is ON
12-29 01:16:42.240 14928-14928/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
12-29 01:16:42.270 14928-14928/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-29 01:16:42.270 14928-14928/? E/android.os.Debug: failed to load memtrack module: -2
12-29 01:16:42.280 14932-14932/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
12-29 01:16:42.290 14928-14928/? I/Radio-JNI: register_android_hardware_Radio DONE
12-29 01:16:42.310 14928-14928/? D/AndroidRuntime: Calling main entry com.android.commands.wm.Wm
12-29 01:16:42.340 14932-14932/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-29 01:16:42.340 14932-14932/? E/android.os.Debug: failed to load memtrack module: -2
12-29 01:16:42.350 14932-14932/? I/Radio-JNI: register_android_hardware_Radio DONE
12-29 01:16:42.370 14932-14932/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
12-29 01:16:42.380 1358-1370/system_process I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.timesavii.getlocation/.GetLocation} from uid 0 on display 0
12-29 01:16:43.560 1358-1488/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 14857 uid 10043
12-29 01:16:43.560 14928-14928/? D/AndroidRuntime: Shutting down VM
12-29 01:16:43.560 1358-1371/system_process W/art: Long monitor contention event with owner method=com.android.internal.view.InputBindResult com.android.server.InputMethodManagerService.windowGainedFocus(com.android.internal.view.IInputMethodClient, android.os.IBinder, int, int, int, android.view.inputmethod.EditorInfo, com.android.internal.view.IInputContext) from InputMethodManagerService.java:2177 waiters=0 for 2.010s
12-29 01:16:43.560 1688-1688/com.google.android.googlequicksearchbox I/Choreographer: Skipped 128 frames!  The application may be doing too much work on its main thread.
12-29 01:16:43.590 1358-1372/system_process W/art: Long monitor contention event with owner method=int com.android.server.am.ActivityStackSupervisor.startActivityMayWait(android.app.IApplicationThread, int, java.lang.String, android.content.Intent, java.lang.String, android.service.voice.IVoiceInteractionSession, com.android.internal.app.IVoiceInteractor, android.os.IBinder, java.lang.String, int, int, android.app.ProfilerInfo, android.app.IActivityManager$WaitResult, android.content.res.Configuration, android.os.Bundle, boolean, int, android.app.IActivityContainer, com.android.server.am.TaskRecord) from ActivityStackSupervisor.java:946 waiters=0 for 750ms
12-29 01:16:43.590 14932-14932/? D/AndroidRuntime: Shutting down VM
12-29 01:16:43.650 1861-1861/com.google.android.googlequicksearchbox:search W/LocationOracleImpl: Best location was null
12-29 01:16:43.700 1861-14948/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
12-29 01:16:43.730 1861-14950/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.speech.audio.u@f8a6cc8
12-29 01:16:43.740 1042-1708/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
12-29 01:16:43.740 1042-14952/? I/AudioFlinger: AudioFlinger's thread 0xf3700000 ready to run
12-29 01:16:43.770 1861-14950/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.speech.audio.u@f8a6cc8
12-29 01:16:43.770 1861-2330/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.speech.audio.u@f8a6cc8
12-29 01:16:43.770 1861-14950/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error -4 during AudioRecord native read
12-29 01:16:43.770 14953-14953/? I/art: Not late-enabling -Xcheck:jni (already on)
12-29 01:16:43.780 1358-1738/system_process I/ActivityManager: Start proc 14953:com.timesavii.getlocation/u0a43 for activity com.timesavii.getlocation/.GetLocation
12-29 01:16:43.860 1861-2333/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Stopping hotword detection.
12-29 01:16:43.980 1861-14948/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Hotword detection finished
12-29 01:16:44.020 1688-1978/com.google.android.googlequicksearchbox E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe12a3690
12-29 01:16:44.060 1861-1871/com.google.android.googlequicksearchbox:search I/art: Background sticky concurrent mark sweep GC freed 3331(258KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 4MB/5MB, paused 80ms total 330ms
12-29 01:16:44.070 14953-14953/com.timesavii.getlocation W/System: ClassLoader referenced unknown path: /data/app/com.timesavii.getlocation-1/lib/x86_64
12-29 01:16:44.100 14953-14953/com.timesavii.getlocation I/GMPM: App measurement is starting up, version: 8487
12-29 01:16:44.100 14953-14953/com.timesavii.getlocation I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
12-29 01:16:44.100 14953-14953/com.timesavii.getlocation E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
12-29 01:16:44.100 14953-14953/com.timesavii.getlocation E/GMPM: Scheduler not set. Not logging error/warn.
12-29 01:16:44.130 14953-14969/com.timesavii.getlocation E/GMPM: Uploading is not possible. App measurement disabled
12-29 01:16:44.230 14953-14963/com.timesavii.getlocation I/art: Background sticky concurrent mark sweep GC freed 15526(955KB) AllocSpace objects, 3(60KB) LOS objects, 52% free, 1833KB/3MB, paused 10ms total 20ms
12-29 01:16:44.270 1030-1181/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
12-29 01:16:44.270 14953-14978/com.timesavii.getlocation D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
12-29 01:16:44.370 14953-14978/com.timesavii.getlocation I/OpenGLRenderer: Initialized EGL, version 1.4
12-29 01:16:44.410 14953-14978/com.timesavii.getlocation W/EGL_emulation: eglSurfaceAttrib not implemented
12-29 01:16:44.410 14953-14978/com.timesavii.getlocation W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f382e3bcc00, error=EGL_SUCCESS
12-29 01:16:44.540 1950-2017/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation()
12-29 01:16:44.640 1358-1370/system_process D/WifiService: acquireWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@f597139}
12-29 01:16:44.730 1950-2017/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation()
12-29 01:16:44.790 1358-1377/system_process I/ActivityManager: Displayed com.timesavii.getlocation/.GetLocation: +1s30ms
12-29 01:16:45.040 1950-2017/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation()
12-29 01:16:45.080 1358-1791/system_process D/WifiService: releaseWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@f597139}
12-29 01:16:54.280 14953-14969/com.timesavii.getlocation I/GMPM: Tag Manager is not found and thus will not be used
12-29 01:19:27.090 1358-1371/system_process I/UsageStatsService: User[0] Flushing usage stats to disk
12-29 01:21:29.890 1358-1369/system_process D/WifiService: acquireWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@f597139}
12-29 01:21:29.900 1358-1488/system_process D/WifiService: releaseWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@f597139}

2 个答案:

答案 0 :(得分:1)

对于当前位置,您可以尝试以下代码:

LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            LocationListener listner = new MyLocationListener();
            location_manager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
            location_manager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

 public class MyLocationListener implements LocationListener {

        StringBuilder str;


        @Override
        public void onLocationChanged(Location arg0) {

            latitude = arg0.getLatitude();
            longitude = arg0.getLongitude();

            try {

                geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
                addresses = geocoder.getFromLocation(latitude, longitude, 1);

                if (geocoder.isPresent()) {

                    Address returnAddress = addresses.get(0);

                    String city = returnAddress.getLocality();
                    String zipCode = returnAddress.getPostalCode();



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

        @Override
        public void onProviderDisabled(String arg0) {
        }

        @Override
        public void onProviderEnabled(String arg0) {
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }
    }

答案 1 :(得分:0)

经过几天的搜索和尝试不同的建议,这就是我发现解决我的问题:

  1. 我的AVD没有安装正确的API,AVD必须有带谷歌播放选项的API。

  2. android studio无法获取位置,它无法访问您的笔记本电脑或PC位置服务。要测试应用是否运行良好并且能够获取位置,我们必须使用工具&gt; android&gt; andriod设备监视器,然后在模拟器控制选项卡中,您可以手动将位置发送到模拟器以获取位置。