三星 Note 2 无法访问 onLocationChanged()

Posted

技术标签:

【中文标题】三星 Note 2 无法访问 onLocationChanged()【英文标题】:Samsung Note 2 can't reach onLocationChanged() 【发布时间】:2015-07-15 09:33:07 【问题描述】:

它适用于除 Galaxy Note 2 之外的大多数设备。它连接到 Google 客户端,但无法访问实现 LocationListeneronLocationChanged()。任何人都知道它是什么原因造成的,为什么只在这个设备上?

@Override
public void onLocationChanged(Location location) 

    mLastLocation = location;

    if (mLastLocation != null) 
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();

        Toast.makeText(getApplicationContext(), String.valueOf(lat) + "/" + String.valueOf(lng), Toast.LENGTH_LONG).show();

        serverUrl = "http://(my server)/offers?lat=" + String.valueOf(mLastLocation.getLatitude())
                            + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=1";
        // save
        makeTag(serverUrl);

        // after getting location data - unregister listener
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mFusedLocationCallback);
        new GetBackgroundUpdate().execute();
     else 
        // get data from server and update GridView
        new GetBackgroundUpdate().execute();
        Toast.makeText(getApplicationContext(), R.string.no_location_detected, Toast.LENGTH_LONG).show();

     
/**
Location methods
*/
protected synchronized void buildGoogleApiClient() 
    mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) 
    // Provides a simple way of getting a device's location and is well suited for
    // applications that do not require a fine-grained location and that do not need location
    // updates. Gets the best and most recent location currently available, which may be null
    // in rare cases when a location is not available.
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(500);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);



@Override
public void onConnectionFailed(ConnectionResult result) 
    // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
    // onConnectionFailed.
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());

    if (mResolvingError) 
        // Already attempting to resolve an error.
        return;
     else if (result.hasResolution()) 
        try 
            mResolvingError = true;
            result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
         catch (IntentSender.SendIntentException e) 
            // There was an error with the resolution intent. Try again.
            mGoogleApiClient.connect();
        
     else 
        // Show dialog using GooglePlayServicesUtil.getErrorDialog()
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(String.valueOf(result.getErrorCode()))
                    .setCancelable(false)
                    .setNegativeButton("Ok", new DialogInterface.OnClickListener() 
                        public void onClick(final DialogInterface dialog, final int id) 
                            dialog.cancel();
                        
                    );
        final AlertDialog alert = builder.create();
        alert.show();
        mResolvingError = true;
    

    //new GetBackgroundUpdate().execute();


@Override
public void onConnectionSuspended(int cause) 
    // The connection to Google Play services was lost for some reason. We call connect() to
    // attempt to re-establish the connection.
    Log.i(TAG, "Connection suspended");
    mGoogleApiClient.connect();


@Override
protected void onStart() 
    super.onStart();
    mGoogleApiClient.connect();


@Override
protected void onStop() 
    super.onStop();
    if (mGoogleApiClient.isConnected()) 
        mGoogleApiClient.disconnect();
    

【问题讨论】:

能否请您发布您的Logcat DistanceFilter.java 中的第 90 行是什么? 地址 = 服务器 + String.valueOf(mLastLocation.getLatitude()) + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=" + distance; 您还没有发布该代码..请也发布相关代码.. 当您引用 mLastLocation 时,它看起来为空。 【参考方案1】:

编辑:从您的评论中NullPointerException 发生的行中,确保mLastLocation 不为空。

if (mLastLocation != null)
    address = server + String.valueOf(mLastLocation.getLatitude()) + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=" + distance;
 

另外需要注意的是,在使用之前,您应该始终确保mGoogleApiClient 不为空且已连接。

if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
  //..... use mGoogleApiClient.....

See documentation here

您还应该添加一项检查以查看 Google Play 服务是否可用,因为有时设备上可用的版本低于您编译应用时使用的版本。如果是这种情况,您可以显示一个对话框。

以下是如何检查 Google Play 服务是否可用。

private boolean isGooglePlayServicesAvailable() 
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) 
            return true;
         else 
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        
    

请注意,getLastLocation() 很容易返回 null,因此如果您从第一次调用 getLastLocation() 中获得 null 值,那么一个好的方法是注册一个位置侦听器。 看到这个帖子:LocationClient getLastLocation() return null

这里是如何注册LocationListener的指南:

创建监听器:

LocationCallback mFusedLocationCallback = new LocationCallback();

类定义:

private class LocationCallback implements LocationListener 

        public LocationCallback() 

        

        @Override
        public void onLocationChanged(Location location) 

                 mLastLocation = location;
                 lat = String.valueOf(mLastLocation.getLatitude());
                 lng = String.valueOf(mLastLocation.getLongitude());


             
    ;

然后只需注册LocationListener

  mLocationRequest = new LocationRequest();
  mLocationRequest.setInterval(minTime);
  mLocationRequest.setFastestInterval(fastestTime);
  mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  mLocationRequest.setSmallestDisplacement(distanceThreshold);

 LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);

编辑:在注册位置回调之前,您应该等待 API 连接,它应该是这样的:

/**
 * Runs when a GoogleApiClient object successfully connects.
 */
@Override
public void onConnected(Bundle connectionHint) 
    // Provides a simple way of getting a device's location and is well suited for
    // applications that do not require a fine-grained location and that do not need location
    // updates. Gets the best and most recent location currently available, which may be null
    // in rare cases when a location is not available.
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) 
        lat = String.valueOf(mLastLocation.getLatitude());
        lng = String.valueOf(mLastLocation.getLongitude());
     else 
        Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
    


     mLocationRequest = new LocationRequest();
     mLocationRequest.setInterval(1000);
     mLocationRequest.setFastestInterval(500);
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);

文档: for requestLocationUpdates.... 和 LocationRequest。

最后一件事,请确保您的 androidManifest.xml 中的 application 标记内包含此内容:

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

【讨论】:

我应该使用 then if(mGoogleApiClient != null && mGoogleApiClient.isConnected() && mLastLocation != null) 吗?它会立即检查所有内容 @jeand'arme 这取决于你在做什么。您不希望在此行之前同时检查所有三个:mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 请注意,getLastLocation() 很容易返回 null,因此如果您获得 null 值,更好的方法是注册位置侦听器。看到这个帖子:***.com/questions/16830047/… 我会尝试使用位置监听器,因为我的应用完全依赖于位置。 @jeand'arme 确保您的兄弟拥有 Google Play 服务的更新版本。如果他需要升级,他应该从getErrorDialog() 呼叫中得到升级提示。不知道维护状态的事情,我稍后有时间会检查一下。 @jeand'arme 是的,这肯定是问题所在。现在的问题是,导致其无法正常工作的根本原因是什么!

以上是关于三星 Note 2 无法访问 onLocationChanged()的主要内容,如果未能解决你的问题,请参考以下文章

解决 三星Note3 桌面小部件不实时更新/不刷新 的问题

即使用户授予位置权限检查,三星 note 20 也总是会被拒绝

三星Note2(N7100)刷机

历代三星Note系列主要参数对比,更新于2021年6月

note5OTA文件夹在哪

如何将数据保存到三星 S3 或 Sansung Note 2 的内部存储器