使用 LocationClient 获取位置更新

2023-12-08

我该如何使用locationclient类与requestLocationUpdates(LocationRequest, LocationListener)在android中获取位置更新?我已经尝试过以下代码,但它不起作用。谁能帮我这个?哪里错了,先谢谢了。

public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener {
private final static int  CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
LocationClient mLocationClient;
Location mCurrentLocation;
LocationRequest mLocationRequest;
ArrayList<Location> list = new ArrayList<Location>();
private static String msg;
private static final int MILLISECONDS_PER_SECOND = 1000; // Milliseconds per second
public static final int UPDATE_INTERVAL_IN_SECONDS = 300;// Update frequency in seconds
private static final long UPDATE_INTERVAL =  MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;  // Update frequency in milliseconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 60;  // The fastest update frequency, in seconds
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
//private EditText text; 
public static class ErrorDialogFragment extends DialogFragment {
    private Dialog mDialog;
    public ErrorDialogFragment() {
        super();
        mDialog = null;                                                 // Default constructor. Sets the dialog field to null
    }
       public void setDialog(Dialog dialog) {
        mDialog = dialog;                                        // Set the dialog to display
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;                                                              // Return a Dialog to the DialogFragment.
    }
}
private final class MyLocationListener implements LocationListener {
     @Override
     public void onLocationChanged(Location location) {
         // Report to the UI that the location was updated
         mCurrentLocation =location;
         Context context = getApplicationContext();

         msg = Double.toString(location.getLatitude()) + "," +  Double.toString(location.getLongitude());
         list.add(mCurrentLocation);

         Toast.makeText(context, msg,Toast.LENGTH_LONG).show();

      }

        }
@Override
protected void onActivityResult(
        int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {

        case CONNECTION_FAILURE_RESOLUTION_REQUEST :
        /*
         * If the result code is Activity.RESULT_OK, try
         * to connect again
         */
            switch (resultCode) {
                case Activity.RESULT_OK :
                /*
                 * Try the request again
                 */

                break;
            }

    }

}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
    mLocationClient = new LocationClient(this, this, this);   /* Create a new location client, using the enclosing class to handle callbacks     */
    mLocationClient.connect();
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);    // Use high accuracy
    mLocationRequest.setInterval(UPDATE_INTERVAL);  // Setting the update interval to  5mins
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);  // Set the fastest update interval to 1 min
    LocationListener locationListener = new MyLocationListener();
    mLocationClient.requestLocationUpdates(mLocationRequest,locationListener);

}

@Override
protected void onDestroy() {
    mLocationClient.disconnect();  
}

/* 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 dataBundle) {

}

/* Called by Location Services if the connection to the location client drops because of an error.*/
@Override
public void onDisconnected() {
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();

}

//Called by Location Services if the at tempt to Location Services fails. 
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * 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()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this,CONNECTION_FAILURE_RESOLUTION_REQUEST);


            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();

        }
    } else {
        /*  * If no resolution is available, display a dialog to the user with the error. */
        showErrorDialog(connectionResult.getErrorCode());
    }
}
private boolean showErrorDialog(int errorCode) {
    int resultCode =
            GooglePlayServicesUtil.
                    isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status

        // Continue
        return true;
    // Google Play services was not available for some reason
    } else {
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode,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");

                        } return false;
            }
        }

}


LocationClient.connect() 是异步的。在连接完成之前,您无法立即开始使用客户端方法。您应该在 onConnected 回调中调用 requestLocationUpdates (或者至少在调用回调之后)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 LocationClient 获取位置更新 的相关文章

  • 如何设置日期选择器的日期?

    I use DatePickerDialog OnDateSetListener效果很好 我想在日期选择器中添加 120 天的日期 我的意思是 如果我添加 120 天 日期和月份将自动更改 怎么做 像这样的事情应该可以解决问题 Calend
  • 现实世界中的 JavaCard 3?

    我目前正在从事我的文凭工作 部分工作包括开发JavaCard常规小程序SIM牌 第一个选项是使用JavaCard2 X API并使用APDU与小程序通信的命令 这可能非常棘手 因为我需要为 android 开发客户端应用程序 它将与这个小程
  • listview getChildAt() 返回 null

    我一直在做一个android项目并陷入了一个问题 我用谷歌搜索但没有找到答案 在我的项目中 有一个名为viewsurahfragment它包含一个 id 为的列表视图lv showquran 我想突出显示指定索引处的列表视图的视图 我正在使
  • Recyclerview 中的 view.GONE 仍保留空间

    我在网上搜索了一下 发现 view invisible 和 view gone 之间有区别 vie gone 必须消失而不保留空间 但它不会发生在我身上 我该如何解决它 请帮忙看看这两张图片的链接 Android模拟器上的结果图 https
  • 更新房间迁移的行

    是否可以编写迁移来更新某个表的所有先前数据 我正在为我的房间数据开发加密 如果我可以在迁移后加密所有行 那就太好了 那么 在定义迁移时 您可以访问支持SQLite数据库 https developer android com referen
  • 更新语言时操作栏未更新

    我目前正在构建一个应用程序 允许人们在应用程序中更新语言 但是 当更改区域设置时 所有字符串都会更新 但操作栏中的字符串不会更新 对应于清单中的活动名称 仅当应用程序从头开始重新启动时才会考虑语言更改 在不强制应用程序重新启动的情况下更新所
  • Android 线程和处理程序不工作

    我最近重构了一个旧项目 发现无论我做什么 特定部分都不再需要正常运行 本质上 我有一个带有 TextView 的 Activity 该视图按时间间隔从同一类中调用的线程更新 暂停是通过 Thread sleep 完成的 并且使用 Handl
  • Appcelerator 与 Android SDK

    我一直在看appcelerator 它看起来很不错 毫无疑问 appcelerator的优势之一就是它对多平台的支持 我有兴趣构建一个 Android 应用程序 也许稍后还会构建一个 iPhone 应用程序 所以目前支持多平台并不重要 如果
  • Fabric Beta 和 APK 拆分

    我根据 ABI 而不是密度来拆分我的应用程序 如下所示 splits abi enable true reset include x86 armeabi armeabi v7a mips arm64 v8a universalApk tru
  • 语音识别和文本转语音

    我想开发一个实现语音识别的应用程序 然后使用文本到语音引擎实现文本到语音 我发布了下面的代码 我使用两个按钮和一个列表视图 一个按钮用于语音识别 另一个按钮用于文本转语音 列表视图用于两者 首先在列表视图中发布语音识别的结果 然后应用程序将
  • LibGDX 闪烁

    我已经使用 LibGDX UI 设置来启动一个项目 我在实现 ApplicationListener 中唯一拥有的是 public void create setScreen new LoadingScreen this 这应该会触发 Lo
  • 以编程方式更改小部件布局

    假设我有两个小部件布局 Layout1 和 Layout2 小部件的默认值是 Layout1 但我允许用户选择 他们希望小部件采用哪种布局 所以如果用户更改为 Layout2 如何以编程方式将布局更改为 Layout2 小部件没有像活动那样
  • 跨平台 IAP

    我已在 iOS 和 Android 中集成了应用内购买 自动续订订阅 两者都工作正常 我对使用跨平台验证 IAP 有一定的疑问 例如 当多个用户登录一个应用程序时 某一特定应用程序的订阅如何运作 例如 如果用户 A 有标准套餐并且从应用程序
  • Android AsyncTask 第二次调用时未执行

    我有一个扩展 AsyncTask 的类 public class SendJSONArray2Server extends AsyncTask
  • ConstraintLayout 源代码位于哪里?

    哪里可以找到android的源代码ConstraintLayout 我在支持框架存储库甚至谷歌搜索中都找不到它 它的源代码在这里 https android googlesource com platform frameworks opt
  • MediaPlayer() 音频口吃(android)

    我正在我的 Android 应用程序中使用 MediaPlayer 函数从远程服务器传输实时音频流 但音频断断续续且断断续续 问题不在于我的互联网 因为当我在计算机上播放时 提要播放得很好 可能是什么问题 注意 直播正在进行中 这是我正在使
  • Android 开发:seekbar 倒计时!

    是否有可能 如果是 如何 如何在用户不执行任何操作的情况下从进度 100 变为 1 就像每0 05秒seekbar setProgress 1 因此 如果用户不执行任何操作 搜索栏就会下降 直到达到 1 请回答如何做到这一点 谢谢 clas
  • Android 依赖项 com.google.firebase:firebase-core 编译 (12.0.1) 和运行时 (11.4.2) 的版本不同

    这是我的项目 Gradle 依赖项 classpath com android tools build gradle 3 1 0 classpath com google gms google services 3 0 0 classpat
  • Android 中的自定义相机应用程序问题 - 旋转 270、拉伸捕获视图且未获取所有功能

    我从代码中得到了帮助https github com josnidhin Android Camera Example https github com josnidhin Android Camera Example 但面临一些问题 例如
  • 当应用程序在 Android 中首次启动时,仅显示一次消息对话框

    我在android中开发了一个应用程序 其中一个重要的要求是仅在应用程序第一次运行时显示语言支持的消息对话框 然后每次用户再次运行应用程序时它都会消失 我 我尝试过使用共享首选项 但没有成功 还有其他方法吗 在 onCreate 处理程序中

随机推荐

  • 与 Typescript 一起使用的 ThemeProvide 出现错误

    我想创建一个组件 const StyledDiv styled div width 10rem height 3rem border radius 0 2rem background color theme colorVariant col
  • R 中近似子串匹配的位置

    我正在使用 R 进行字符串处理 我有一个带有一列字符串的数据框 例如 df lt data frame textcol c In this substring would like to find the position of this
  • Apache Beam Google Datastore ReadFromDatastore 实体 protobuf

    我正在尝试使用 apache beam 的 google datastore api 来 ReadFromDatastore p beam Pipeline options options p Read from Datastore gt
  • 宏重载

    是否可以定义这样的东西 define FOO x y BAR define FOO x sth y BAR sth 这样 FOO daf sfdas FOO fdsfs something 5 翻译成这样 BAR BAR something
  • UITableViewController 中的状态栏

    我用一个UITableViewController into a Navigation Controller当出现UIButton按下 当按钮被按下时TableViewController出现时没有状态栏 如果我选择一个单元格TableVi
  • FRestore文档onUpdate:仅针对特定字段触发

    在我的云功能中 我有下一个功能 export const collectionOnUpdate functions firestore document cards id onUpdate async change context gt a
  • Node.js + Socket.io |在服务器上设置自定义标头

    我使用 Helmet 和 Express 从服务器端设置相当多的安全 HTTP 标头 当在 Node js 应用程序顶部渲染客户端页面时 使用以下命令 这做得很好 var app express app use helmet res ren
  • 在另一个 IQueryable 中使用 IQueryable

    我有一个扩展方法 它返回一个 IQueryable 来获取公司产品 我只想在 IQueryable 中使用它作为子查询 public static class DBEntitiesCompanyExtensions public stati
  • 通过 JSF 将 PDF 发送到浏览器

    我正在尝试将 JasperReports 生成的 PDF 文件发送到用户的浏览器 我找不到托管 bean 方法中的问题 以下是一个片段 System out println Making pdf FacesContext fc FacesC
  • Windows Phone 8 上的 HttpWebRequest 同步

    为了设计 重用可用于 WPF 应用程序 Windows Phone 8 应用程序和更高版本的 Windows 8 RT 应用程序的库 我们需要进行一些 HttpWebRequest 调用 最好是同步调用 以免破坏现有应用程序 问题是已经存在
  • 使用 AJAX 和 JQuery 通过 PHP 进行简单验证

    我是新来的AJAX 我想学习如何验证表单 假设我有一个带有两个输入字段的表单 当我点击提交时 我想用 php 脚本检查页面 验证成功后我想重定向到action submitForm php 当一个或多个字段根据validation php我
  • OpenVINO:如何使用推理引擎构建 OpenCV 以支持从模型优化器加载模型

    我安装了 OpenVINO 并想在 Windows 10 上运行以下代码 import numpy as np import cv2 import sys from get face id import face id getter fro
  • 如何在 Oracle 11gr2 中安装 Procedural Option

    我一直在尝试在计算机上本地安装的 Oracle 11gR2 上创建 PL SQL 包并运行过程 但一直收到 ORA 00900 错误 基于此article 看来Procedural Option还没有安装 这是我登录时 sqlplus 的输
  • 事件驱动编程如何帮助仅执行 IO 的 Web 服务器?

    我正在考虑为我们的新后端项目使用一些框架 编程方法 它涉及 BackendForFrontend 实现 聚合下游服务 为简单起见 以下是它所经历的步骤 请求进入网络服务器 Web服务器发出下游请求 下游请求返回结果 Web服务器返回请求 事
  • CodeIgniter 2.0 - 验证数组

    我在将一段表单验证代码转换为 CI 2 0 时遇到一些问题 我正在尝试验证一组复选框 但由于某种原因验证无法运行回调或不验证 如何验证一组复选框 以便至少选中一个并且值必须是选项之一 选项数组的键 EDIT 这是对我失败的地方的更好解释 可
  • 使用 na.approx 在数据框中插入 NA 值

    我正在尝试删除NA通过插值从我的数据框中获取na approx 但无法删除所有NAs 我的数据帧是 4096x4096 其中 270 15 作为无效值的标志 我需要在所有点上连续的数据来提供气象模型 昨天我询问并获得了关于如何基于另一个数据
  • 循环创建PyQt5按钮:所有按钮触发相同的回调

    我应该提到 我已经阅读了这些内容 但我仍然无法实现我的目标 在 for 循环中使用字典来创建按钮不起作用 循环中的 QtCore QObject connect 仅影响最后一个实例 我的目标是制作一个 Linux 启动器 应用程序 按钮的创
  • session_start() 错误

    我无法处理这个错误 请帮助我 它可以在我的笔记本电脑上运行 但不能在我的台式机上运行 Why Warning session start function session start Cannot send session cache li
  • 如何让代码在Response.end之后执行

    我的代码是这样的 HttpContext Current Response Clear HttpContext Current Response ContentType application pdf HttpContext Current
  • 使用 LocationClient 获取位置更新

    我该如何使用locationclient类与requestLocationUpdates LocationRequest LocationListener 在android中获取位置更新 我已经尝试过以下代码 但它不起作用 谁能帮我这个 哪