如何在BroadcastReceiver类中检索GPS坐标

时间:2011-06-29 17:56:09

标签: android gps sms broadcastreceiver

我的BroadcastReceiver类中有一个方法,它检查sms触发器并根据触发的触发器执行函数。这是一种过滤短信内容并返回msg以在响应短信中发送的方法。

我目前有条件在“定位器”条件下将locationListener注册到网络/ GPS。但是,在正确搜索坐标数据之前,我一直在返回带有空白内容的“msg”。

我确实试过了一个while循环,但是我让它跳了起来,我怀疑是一个无限循环。 还尝试了startActivityResult但无法使用。

请建议。

public String methodTrigger(Context context, String operation){
        String returnMsg="";

        if (operation.equalsIgnoreCase("Lock")){
            Intent lock = new Intent(context, lockscreen.class);
            lock.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(lock);
            returnMsg = "Lock Operation Enabled";
        }else if(operation.equalsIgnoreCase("Locate")){
            String msg = "";
            Log.i("monitor", "Create");
            LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    // Called when a new location is found by the network location provider.
                    int lat = (int) (location.getLatitude() * 1E6);
                    int lng = (int) (location.getLongitude() * 1E6);
                    test = "Latitude: "+String.valueOf(lat)+"\nLongitude: "+String.valueOf(lng);
                    Log.i("monitor", "Reading coordintes");
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {}
                public void onProviderEnabled(String provider) {}
                public void onProviderDisabled(String provider) {}
            };

            // Register the listener with the Location Manager to receive location updates
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                Log.i("monitor", "Listen Network");
            }else{
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                Log.i("monitor", "Listen GPS");
            }
            Log.i("monitor", "Finish");
            returnMsg = test;
        }else if(...other functions.....
        }
        return returnMsg;
    }

1 个答案:

答案 0 :(得分:0)

你不能这样做,因为methodTrigger在调用onLocationChanged之前返回。