位置侦听器从服务工作,但不是 IntentService

2024-03-12

我有一个应用程序,我试图定期获取用户位置并将其发送到服务器。我有一项服务附加到AlarmManager每分钟执行一次(用于测试)。该服务正确找到用户位置并注销 GPS 坐标。一旦出现 GPS 锁定,我就会取消位置请求并停止服务。当我请求位置更新时,我启动Handler20秒后执行,这个Handler删除位置更新并停止Service如果没有实现锁定。这一切都有效。

下面是使用以下代码工作的代码Service class.

public class TrackingService extends Service {

    private static final String TAG = TrackingService.class.getSimpleName();
    LocationManager             mlocManager;
    LocationListener            mlocListener;
    NfcScannerApplication       nfcscannerapplication;
    String carerID;

    Handler endServiceHandler;
    Runnable endServiceRunnable;

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

        nfcscannerapplication = (NfcScannerApplication) getApplication();
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();

        Log.e(TAG, "Service created and location manager and listener created");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "in onDestroy in LocationService class");
        mlocManager.removeUpdates(mlocListener);


    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        Log.e(TAG, "requesting location updates");

        enableMenuButtonsHandler();
        endServiceHandler.postDelayed(endServiceRunnable,20 * 1000);
    }

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

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {


            Log.e(TAG, "in TrackingService onlocationChanged and about to send lon/lat " + loc.getLongitude() + " " + loc.getLatitude());


            DateTime dt = new DateTime();
            DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
            String formattedNowTime3 = df3.print(dt);
            Log.e(TAG, "Time of location fix in TrackingServive = " + formattedNowTime3);


            Cursor c = nfcscannerapplication.loginValidate.queryAllFromCarer();

            if (c.getCount() > 0) {
                if(c.moveToLast()){

                carerID = c.getString(c.getColumnIndex(LoginValidate.C_CARER_ID));

                }
            }

             Log.e(TAG, "carer ID = " + carerID);

             mlocManager.removeUpdates(mlocListener);
             Log.e(TAG, "removed updates(TrackingService)");

             TrackingService.this.stopSelf();
             Log.e(TAG, "called stopSelf on TrackingService");

        }

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

        }

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

        }

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

        }

    }// end of MyLocationListener


    public void enableMenuButtonsHandler() {

        endServiceHandler = new Handler();
        endServiceRunnable = new Runnable() {
            public void run() {

                endService();

            }

            private void endService() {

                 mlocManager.removeUpdates(mlocListener);
                 Log.e(TAG, "removed updates(TrackingService) from the endService handler");

                 TrackingService.this.stopSelf();
                 Log.e(TAG, "called stopSelf on TrackingService from the endService handler");

            }
        };

    }


}// end of service 

我遇到的问题是一旦我有了 GPS 锁,我想将长和纬度坐标发送到服务器。我知道我可以使用AsyncTask from a Service但我不想这样做。我更愿意使用IntentService因为它在自己的后台线程中运行。这样我就可以直接从IntentService.

下面的代码实现了IntentService类,但似乎没有获得锁定。 GPS 会无限期地在手机上闪烁。日志记录语句最多达到“请求位置更新”,然后就什么也没有了。

有谁知道为什么没有实现锁定?提前致谢。

public class TrackingService extends IntentService {

   private static final String TAG = TrackingService.class.getSimpleName();
   LocationManager             mlocManager;
   LocationListener            mlocListener;
   NfcScannerApplication       nfcscannerapplication;
   String carerID;

   Handler endServiceHandler;
   Runnable endServiceRunnable;

    public TrackingService() {
        super("TrackingService");

    }

    @Override
    protected void onHandleIntent(Intent intent) {

           nfcscannerapplication = (NfcScannerApplication) getApplication();
           mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
           mlocListener = new MyLocationListener();
           Log.e(TAG, "Service created and location manager and listener created");

           mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
           Log.e(TAG, "requesting location updates");

           enableMenuButtonsHandler();
           endServiceHandler.postDelayed(endServiceRunnable,20 * 1000);

    }



     private class MyLocationListener implements LocationListener {

                 @Override
                 public void onLocationChanged(Location loc) {


                    Log.e(TAG, "in TrackingService onlocationChanged and about to send lon/lat " + loc.getLongitude() + " " + loc.getLatitude());


                     DateTime dt = new DateTime();
                     DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
                     String formattedNowTime3 = df3.print(dt);
                     Log.e(TAG, "Time of location fix in TrackingServive = " + formattedNowTime3);


                     Cursor c = nfcscannerapplication.loginValidate.queryAllFromCarer();

                    if (c.getCount() > 0) {
                        if(c.moveToLast()){

                        carerID = c.getString(c.getColumnIndex(LoginValidate.C_CARER_ID));

                        }
                    }

                     Log.e(TAG, "carer ID = " + carerID);

                     mlocManager.removeUpdates(mlocListener);
                     Log.e(TAG, "removed updates(TrackingService)");

                     TrackingService.this.stopSelf();
                     Log.e(TAG, "called stopSelf on TrackingService");

                 }

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

                 }

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

                 }

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

                 }

             }// end of MyLocationListener


     public void enableMenuButtonsHandler() {

                endServiceHandler = new Handler();
                endServiceRunnable = new Runnable() {
                    public void run() {

                        endService();

                    }

                    private void endService() {

                         mlocManager.removeUpdates(mlocListener);
                         Log.e(TAG, "removed updates(TrackingService) from the endService handler");

                         TrackingService.this.stopSelf();
                         Log.e(TAG, "called stopSelf on TrackingService from the endService handler");

                    }
                };

     }

}//end of trackingService

[Edit1]

public class TrackingService extends Service {

    private static final String TAG = TrackingService.class.getSimpleName();
    LocationManager             mlocManager;
    LocationListener            mlocListener;
    NfcScannerApplication       nfcscannerapplication;
    String carerID;

    Handler endServiceHandler;
    Runnable endServiceRunnable;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        nfcscannerapplication = (NfcScannerApplication) getApplication();
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();

        Log.e(TAG, "Service created and location manager and listener created");

        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        Log.e(TAG, "requesting location updates");

        enableMenuButtonsHandler();
        endServiceHandler.postDelayed(endServiceRunnable, 20 * 1000);

            return super.onStartCommand(intent, flags, startId);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "in onDestroy in LocationService class");
        mlocManager.removeUpdates(mlocListener);


    }








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

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {


            Log.e(TAG, "in TrackingService onlocationChanged and about to send lon/lat " + loc.getLongitude() + " " + loc.getLatitude());


            DateTime dt = new DateTime();
            DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
            String formattedNowTime3 = df3.print(dt);
            Log.e(TAG, "Time of location fix in TrackingServive = " + formattedNowTime3);


            Cursor c = nfcscannerapplication.loginValidate.queryAllFromCarer();

            if (c.getCount() > 0) {
                if(c.moveToLast()){

                carerID = c.getString(c.getColumnIndex(LoginValidate.C_CARER_ID));

                }
            }

             Log.e(TAG, "carer ID = " + carerID);

             mlocManager.removeUpdates(mlocListener);
             Log.e(TAG, "removed updates(TrackingService)");

             TrackingService.this.stopSelf();
             Log.e(TAG, "called stopSelf on TrackingService");

        }

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

        }

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

        }

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

        }

    }// end of MyLocationListener


    public void enableMenuButtonsHandler() {

        endServiceHandler = new Handler();
        endServiceRunnable = new Runnable() {
            public void run() {

                endService();

            }

            private void endService() {

                 mlocManager.removeUpdates(mlocListener);
                 Log.e(TAG, "removed updates(TrackingService) from the endService handler");

                 TrackingService.this.stopSelf();
                 Log.e(TAG, "called stopSelf on TrackingService from the endService handler");

            }
        };

    }


}// end of service 

[Edit2]

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        nfcscannerapplication = (NfcScannerApplication) getApplication();
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();
        Log.e(TAG, "Service created and location manager and listener created");


            HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
            handlerThread.start();
            Looper looper = handlerThread.getLooper();

            Handler handler = new Handler(looper);

        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener, looper);
        Log.e(TAG, "requesting location updates");

        enableMenuButtonsHandler();
        endServiceHandler.postDelayed(endServiceRunnable, 20 * 1000);

            return super.onStartCommand(intent, flags, startId);
    }

[Edit3]

public class TrackingService extends Service {

    private static final String TAG = TrackingService.class.getSimpleName();
    LocationManager             mlocManager;
    LocationListener            mlocListener;
    NfcScannerApplication       nfcscannerapplication;
    String carerID;

    Handler endServiceHandler;
    Runnable endServiceRunnable;
    HandlerThread handlerThread;
    Looper looper;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        nfcscannerapplication = (NfcScannerApplication) getApplication();
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();
        Log.e(TAG, "Service created and location manager and listener created");


            Log.e(TAG, "creating handlerthread and looper");
            handlerThread = new HandlerThread("MyHandlerThread");
            handlerThread.start();
            looper = handlerThread.getLooper();





        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener, looper);
        Log.e(TAG, "requesting location updates");

        enableMenuButtonsHandler();
        endServiceHandler.postDelayed(endServiceRunnable, 20 * 1000);

            return super.onStartCommand(intent, flags, startId);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "in onDestroy in LocationService class");
        mlocManager.removeUpdates(mlocListener);


    }







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

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {


            Log.e(TAG, "in TrackingService onlocationChanged and about to send lon/lat " + loc.getLongitude() + " " + loc.getLatitude());


            DateTime dt = new DateTime();
            DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
            String formattedNowTime3 = df3.print(dt);
            Log.e(TAG, "Time of location fix in TrackingServive = " + formattedNowTime3);


            Cursor c = nfcscannerapplication.loginValidate.queryAllFromCarer();

            if (c.getCount() > 0) {
                if(c.moveToLast()){

                carerID = c.getString(c.getColumnIndex(LoginValidate.C_CARER_ID));

                }
            }

             Log.e(TAG, "carer ID = " + carerID);

             nfcscannerapplication.loginWebservice.sendCarerLocation(carerID, formattedNowTime3, String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()));



             Log.e(TAG, "quiting handlerthread");
             handlerThread.quit();

             mlocManager.removeUpdates(mlocListener);
             Log.e(TAG, "removed updates(TrackingService)");

             TrackingService.this.stopSelf();
             Log.e(TAG, "called stopSelf on TrackingService");

        }

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

        }

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

        }

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

        }

    }// end of MyLocationListener


    public void enableMenuButtonsHandler() {

        endServiceHandler = new Handler();
        endServiceRunnable = new Runnable() {
            public void run() {

                endService();

            }

            private void endService() {

                 mlocManager.removeUpdates(mlocListener);
                 Log.e(TAG, "removed updates(TrackingService) from the endService handler");

                 TrackingService.this.stopSelf();
                 Log.e(TAG, "called stopSelf on TrackingService from the endService handler");

                 Log.e(TAG, "quiting handlerthread from the endService handler");
                 handlerThread.quit();

            }
        };

    }


}// end of service

正如 Pankaj Kumar 指出的那样,IntentService对于要完成的工作本质上是异步的情况来说,这不是一个合适的解决方案。一次onHandleIntent()退货,你的服务就被破坏了。

使用常规的Service,注册位置onStartCommand(), 用一个HandlerThread用于处理结果(这样你就可以传递它的Looper into requestLocationUpdates())。收到您的位置或达到合适的超时时间后,即可开始工作并致电stopSelf()上的服务将其关闭。

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

位置侦听器从服务工作,但不是 IntentService 的相关文章

随机推荐

  • 微服务架构中的开发环境搭建[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们正致力于在微服务架构中开发网络应用程序 我们考虑在 API 网关后面运行服务 该网关将处理身份验证并将请求代理到适当的服务 我们在
  • 有没有更简单的方法在 Java 中签署 XML 文档?

    我试图对 XML 文档进行数字签名 http www w3 org TR xmldsig core 使用Java 我有一个与一些参考文献一起使用的实现 我发现它们在javax xml crypto dsig http java sun co
  • 使用 CSS 根据图像所在 DIV 的大小调整图像大小?

    下面是我正在开发的博客的图片 不过我需要一些 CSS 方面的帮助 在上图中 您可以看到当我的头像右侧的文本正文大于图像时 它会发生什么情况 下图是我想要的样子 我的问题是有多个作者 因此右侧的正文可能会根据作者的不同而具有不同的长度 我想以
  • 如何使用核心蓝牙框架获取数据?

    我正在开发一个iOS核心蓝牙应用程序 我可以使用iphone4S连接蓝牙设备 但我不知道如何与设备通信 我想从设备读取信息 我也看到这个源代码https github com sergiomtzlosa CoreBluetooth Demo
  • LINQ 选择列表,其中子列表包含另一个列表中的项目

    我不知道如何创建这个查询 如果项目 Cats 列表包含与 List2 中其中一只猫的 ID 匹配的 Cat 对象 我需要选择列表 1 中的项目 这可能吗 谢谢 List1
  • 如何在反应中隐藏登录和注册页面中的导航栏?

    我的路线是这样的
  • 两个字符串序列中的最长公共子串

    刚刚学习了最长公共子串算法 我对这个问题的一个特定变体感到好奇 其描述如下 给定两个非空字符串序列 X x1 x2 x3 x n 和 Y y1 y2 y3 y m 其中 x i 和 y i 是字符串 求longestX 中的字符串 它是al
  • 读取内存映射的 bzip2 压缩文件

    所以我正在使用维基百科转储文件 它是一个经过 bzip 压缩的 XML 文件 我可以将所有文件写入目录 但是当我想做分析时 我必须重新读取磁盘上的所有文件 这使我可以随机访问 但速度很慢 我有 ram 将整个 bzipped 文件放入 ra
  • 使用嵌套转发器对一组数据集进行分组

    假设我有一些这样的书籍数据 我有一个查询 例如SELECT FROM BookData以上述格式输出 我想使用嵌套的转发器控件来输出 html 中的数据 table 看起来像这样 数据结果按作者分组 到目前为止 我的 asp net Web
  • 对热图的刻度线进行分组

    I have a heatmap that looks like this from Plotting a 2D heatmap with Matplotlib https stackoverflow com questions 33282
  • 使用 JTable 作为 JTree 单元格编辑器

    我想使用 JTable 来编辑 JTree 我扩展了 DefaultTreeCellEditor 并实现了 isCellEditable getTreeCellEditorComponent 在 getTreeCellEditorCompo
  • 有 DGML 查看器吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我已经开始玩了DGML http en wikipedia org wiki DGML用于基于某些制造
  • 现在 x86 上有多少指令? [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 我正在尝试
  • 仅使用套接字的 Python 邮件客户端(无 smtplib)

    我正在尝试编写一个 python 程序 它将在不使用 smtplib 的情况下发送电子邮件 我尝试查看有关此问题的其他帖子 但找不到解决方案 from socket import msg r n My email s content end
  • Spring MVC 项目无法发布和运行...消息:无法自省注释

    我有一个 Spring MVC 应用程序 4 1 1 发布版本 当我尝试发布并在服务器上运行时 我收到以下错误 附加信息 使用Spring工具套件3 6 1 春季版本 4 1 1 RELEASE 这是一个maven项目 它没有任何编译错误
  • OCMock - 部分模拟 [UIAlertView alloc]

    我有一个问题OCMockiOS 框架 我本质上是想嘲笑UIAlertView s initWithTitle message delegate 方法 下面的示例不起作用 因为当我调用时 未返回存根返回值initWithTitle metho
  • 使用 Gson 2.3.1 反序列化包含在 Java 中不起作用的接口的 Json 字符串

    我正在尝试使用 Gson 将包含接口和哈希图 具有接口类型和包含接口类型的列表 的 json 字符串反序列化为 java 对象 但我越来越 java lang RuntimeException 无法调用接口 com abc Dummy 的无
  • R - 使用匹配运算符时保留顺序 (%in%)

    我正在使用匹配运算符从单独的数据框中获取矩阵中出现的值 但是 生成的矩阵的值按照它们在数据框中出现的顺序排列 而不是按原始矩阵排列 有没有办法使用匹配运算符来保留原始矩阵的顺序 这是一个简单的例子 vec c b a c vec df da
  • jQuery 克隆表行

    我有一个表 末尾有一个 添加 按钮 当您单击此按钮时 我希望在当前行下方创建一个新的表行 我还希望该行的输入字段为空 我尝试使用 clone 来执行此操作 但它会克隆页面上的所有行 请帮忙 谢谢 Script input tr clone
  • 位置侦听器从服务工作,但不是 IntentService

    我有一个应用程序 我试图定期获取用户位置并将其发送到服务器 我有一项服务附加到AlarmManager每分钟执行一次 用于测试 该服务正确找到用户位置并注销 GPS 坐标 一旦出现 GPS 锁定 我就会取消位置请求并停止服务 当我请求位置更