当前位置: 首页 > 知识库问答 >
问题:

LocationClient只在某些设备上工作

桂高昂
2023-03-14

我正试图在后台获取用户位置。在我的手机(htc one m7)上一切都很好,但出于某种原因,它不能在我测试的两个设备上工作:三星galaxy s3索尼Xperia Z1

顺便说一句:我把所有东西都添加到了清单中。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;

public class BackgroundLocationService extends Service implements
  GooglePlayServicesClient.ConnectionCallbacks,
  GooglePlayServicesClient.OnConnectionFailedListener {

IBinder mBinder = new LocalBinder();

private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;

private Boolean servicesAvailable = false;

public class LocalBinder extends Binder {
    public BackgroundLocationService getServerInstance() {
        return BackgroundLocationService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();


    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(0);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1);

    servicesAvailable = servicesConnected();

    /*
     * Create a new location client, using the enclosing class to
     * handle callbacks.
     */
    mLocationClient = new LocationClient(this, this, this);


}

private boolean servicesConnected() {

    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {

        return true;
    } else {

        return false;
    }
}

public int onStartCommand (Intent intent, int flags, int startId)
{
    super.onStartCommand(intent, flags, startId);

    if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();
    if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
    {
        mInProgress = true;
        mLocationClient.connect();
    }

    return START_STICKY;
}

/*
 * Create a new location client, using the enclosing class to
 * handle callbacks.
 */
private void setUpLocationClientIfNeeded()
{
    if(mLocationClient == null) 
        mLocationClient = new LocationClient(this, this, this);
}

// Define the callback method that receives location updates


@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}



public void appendLog(String text, String filename)
{       
   File logFile = new File(filename);
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

@Override
public void onDestroy(){
    // Turn off the request flag
    mInProgress = false;
    if(servicesAvailable && mLocationClient != null) {
        //mLocationClient.removeLocationUpdates(callbackIntent);
        // Destroy the current location client
        mLocationClient = null;
    }
    // Display the connection status
    // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
    super.onDestroy();  
}

/*
 * Called by Location Services when the request to connect the
 * client finishes successfully. At this point, you can
 * request the current location or start periodic updates
 */
@Override
public void onConnected(Bundle bundle) {

    // Request location updates using static settings
    Intent intent = new Intent(this, LocationReceiver.class);
      PendingIntent locationIntent = PendingIntent.getBroadcast(getApplicationContext(), 14872, intent, PendingIntent.FLAG_CANCEL_CURRENT);
      mLocationClient.requestLocationUpdates(mLocationRequest, locationIntent);
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onDisconnected() {
    // Turn off the request flag
    mInProgress = false;
    // Destroy the current location client
    mLocationClient = null;
    // Display the connection status
    // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}

/*
 * Called by Location Services if the attempt to
 * Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;

    /*
     * 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 (connectionResult.hasResolution()) {

    // If no resolution is available, display an error dialog
    } else {

    }
}


}
import java.util.List;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
 import android.util.Log;

import com.google.android.gms.location.LocationClient;

public class LocationReceiver extends BroadcastReceiver {
public static double lat;
public static double alt;
public static String address;


@Override
public void onReceive(Context context, Intent intent) {

    Location location = (Location) intent.getExtras().get(LocationClient.KEY_LOCATION_CHANGED);
    Log.d("New Location Reciver", "location "+location.toString());

    lat = location.getLatitude();
    alt = location.getAltitude();
    address = getAddressByCord(lat, alt, context);
}


public static String getAddressByCord(double lat, double longi, Context context) {

    try {
        Geocoder geo = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = geo.getFromLocation(lat, longi, 1);
        if (addresses.isEmpty()) {
            return "Waiting for Location";
        } else {
            if (addresses.size() > 0) {
                String s = "";
                if (addresses.get(0).getFeatureName() != null)
                    s += addresses.get(0).getFeatureName();
                if (addresses.get(0).getThoroughfare() != null)
                    s += "," +          addresses.get(0).getThoroughfare();
                if (addresses.get(0).getLocality() != null)
                    s += "," + addresses.get(0).getLocality();
                if (addresses.get(0).getAdminArea() != null)
                    s += "," + addresses.get(0).getAdminArea();
                if (addresses.get(0).getCountryName() != null)
                    s += "," +   addresses.get(0).getCountryName();
                return s;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
}

共有1个答案

许淳
2023-03-14

检查google play服务的代码

private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 94378;

private boolean isGooglePlay() {
    int mIsGooglePlayServicesAvailable = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(context);

    switch (mIsGooglePlayServicesAvailable) {
    case ConnectionResult.SUCCESS:
        return true;
    default:
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                mIsGooglePlayServicesAvailable, this,
                CONNECTION_FAILURE_RESOLUTION_REQUEST);
        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);
            // Show the error dialog in the DialogFragment
            errorFragment.show(getSupportFragmentManager(),
                    "Location Updates");
        }
        // case ConnectionResult.SERVICE_MISSING:
        // case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
        // case ConnectionResult.SERVICE_DISABLED:
        // case ConnectionResult.SERVICE_INVALID:
        // case ConnectionResult.DATE_INVALID:
    }
    return false;
}

/*
 * This is a class used to resolve errors with google play services It is
 * copied code that doesn't run durring normal operation.
 */
public static class ErrorDialogFragment extends DialogFragment {
    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}
 类似资料:
  • 我的Android应用程序无法安装在一些“随机”、较旧的API设备上(任何低于API级别25的设备),错误如下: 所以,基本上看起来… API 我见过类似的问题,答案与小写的包名有关。我已经有了。 有人有什么想法吗? 舱单: BTW我用的是Visual Studio 2019和一夫一妻制3.7

  • 最近,我们在Android应用程序中增加了对Chromecast的支持,但在对各种移动设备(手机和平板电脑)的扩展测试中,发现在许多移动设备上,Flipps应用程序都没有发现Chromecast。在相同的设备上,我们使用了最新版本的官方Chromecast SDK演示应用程序进行测试,该应用程序从https://github.com/googlecast/castvideo-Android下载(主

  • 问题内容: 我看到Google Play中与Fabric / Crashlytics相关的崩溃。从正常的Crashlytics更新到新的Fabric Crashlytics之后,发生了这种情况。我只能在其中一台设备(Galaxy S2)上重现它。我拥有的所有其他设备(Nexus 5和S4)都没有崩溃。这是堆栈跟踪: 这是我的build.gradle的内容: 问题答案: 我只是凭直觉就知道了!升级到

  • 嗨,我正在尝试开发一个具有完全透明状态栏和白色导航栏的页面。我正在使用 但是它在某些设备上不起作用。它在某些设备上显示状态栏的覆盖。不过,它在某些设备上工作正常。请帮我解决这个问题。我也尝试过设置全屏标志,但它会导致状态栏字体消失。我也使用了statusBarUtil库,但它会导致导航栏变黑。

  • 我是android开发的新手。我正在从事一个项目,该项目有不同的活动,其中两个使用jSon解析。 我的问题是,即使在测试时,我的ap在一些设备上工作正常,但在一些设备上失败了。关于这个问题,我看了无数的回答,但是没有一个能解决我的问题。我也有一些其他问题,但我通过查看可用的答案解决了它们,但这个“未安装”的问题仍然是一样的。我做到了以下几点: 创建签名apk 签署了带有“发布”选项的apk 两个选

  • 问题内容: 我正在尝试获取文件的大小,然后再下载。我曾经这样做,它在我的家用计算机Android 2.1 Emulator上运行良好。 但是,一旦我从手机(WiFi或3G)运行我的应用程序,该功能将无法使用,而当我从工作笔记本电脑的Android 2.1仿真器中运行该应用程序时,它也将无法使用。 有谁知道解决方法?还有另一种方法可以获取文件的大小,而无需使用。 问题答案: 此信息并非始终可用。通常