如何获取每半小时android的位置更新?

时间:2013-04-29 16:19:40

标签: android locationmanager

您好我已经开发了一个Android应用程序来获取位置并将其发送到服务器它工作正常,但位置更新无法正常运行它一旦运行我必须获取位置并在半小时内发送到服务器一次,这个过程应该只运行9小时到17小时我该怎么办呢请帮助我..!

我的代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        {

            Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
            intent.putExtra("enabled", true);
            this.sendBroadcast(intent);

            String provider = Settings.Secure.getString(getContentResolver(),
                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if (!provider.contains("gps")) { // if gps is disabled
                final Intent poke = new Intent();
                poke.setClassName("com.android.settings",
                        "com.android.settings.widget.SettingsAppWidgetProvider");
                poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                poke.setData(Uri.parse("3"));
                this.sendBroadcast(poke);

                manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                String providerName = manager.getBestProvider(new Criteria(),
                        true);
                Location location = manager.getLastKnownLocation(providerName);

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

                    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
                            .getCellLocation();
                    String networkOperator = mTelephonyManager
                            .getNetworkOperator();

                    Log.d("CID", Integer.toString(loc.getCid()));
                    Log.d("LAC", Integer.toString(loc.getLac()));
                    int mcc = Integer.parseInt(networkOperator.substring(0, 3));
                    int mnc = Integer.parseInt(networkOperator.substring(3));

                    TextView tv1 = (TextView) findViewById(R.id.locationResults);
                    if (loc != null) {
                        tv1.setText("Cell ID: " + loc.getCid() + " , "
                                + "Lac: " + loc.getLac() + "mcc : " + mcc
                                + "mnc : " + mnc);

                    }

                    // manager.requestLocationUpdates(providerName, 1000 * 60 *
                    // 2, 0,this);

                }

            }

            else {

                String providerName = manager.getBestProvider(new Criteria(),
                        true);
                Location location = manager.getLastKnownLocation(providerName);

                TextView tv = (TextView) findViewById(R.id.locationResults);
                if (location != null) {
                    tv.setText(location.getLatitude() + " latitude, "
                            + location.getLongitude() + " longitude");

                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    telephonyManager.getDeviceId();
                    String imei = telephonyManager.getDeviceId();

                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss");
                    String cdt = sdf.format(new Date());

                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();

                    String lat = Double.toString(latitude);
                    String lon = Double.toString(longitude);

                    String locations = Double.toString(latitude) + ","
                            + Double.toString(longitude);


                    // manager.requestLocationUpdates(providerName, 1000 * 60 *
                    // 2, 0,this);

                }

                else {

                    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
                            .getCellLocation();
                    String networkOperator = mTelephonyManager
                            .getNetworkOperator();

                    Log.d("CID", Integer.toString(loc.getCid()));
                    Log.d("LAC", Integer.toString(loc.getLac()));
                    int mcc = Integer.parseInt(networkOperator.substring(0, 3));
                    int mnc = Integer.parseInt(networkOperator.substring(3));

                    // TextView tv1 = (TextView)
                    // findViewById(R.id.locationResults);
                    if (loc != null) {
                        tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
                                + loc.getLac() + "mcc : " + mcc + "mnc : "
                                + mnc);

                    }

                }

                manager.requestLocationUpdates(providerName, 1000 * 60 * 10, 1,
                        this);
            }
        }
    }

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        // sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
                + ((lon - curStatLon) * (lon - curStatLon)));
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

    }

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView) findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, "
                    + location.getLongitude() + " longitude");
        } else {
            tv.setText("Problem getting gps NETWORK ID : ");

        }
    }



    @Override
    public void onProviderDisabled(String arg0) {

    }

    @Override
    public void onProviderEnabled(String arg0) {
    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    }

}

3 个答案:

答案 0 :(得分:2)

您可以使用LocationManager类的requestLocationUpdates

  

requestLocationUpdates(long minTime,float minDistance,Criteria   标准,PendingIntent intent)

所以,你可以根据你的要求指定第一个参数为30分钟。

要记录经过的小时数,您可以使用以下内容:

var1 = System.CurrentTimeMillis(); //Get time when service started

onLocationChanged()

var2 = System.CurrentTimeMillis();

现在计算var2-var1以获取已用时间。如果&gt; 17小时,removeUpdates来自locationManager

答案 1 :(得分:0)

我有一个类似的项目,我正在使用服务,由 AlarmManager 解雇。 查看here了解详情。

答案 2 :(得分:0)

Schaemelhout提供的方法和评论中提到的图书馆采取的方法是我找到的唯一可行的解​​决方案。

使用AlarmManager唤醒服务可确保定期调用/重新启动服务。这可以抵消操作系统/电话可能在同一时间点击您的服务的任何节电操作。

从警报中注册位置监听器BroadcastReceiver唤醒GPS(如果电话处于睡眠状态,GPS通常不会运行)。在你的警报BroadcastReceiver中,你需要拿起一个WakeLock并保持清醒,直到结果传回给听众。

这种方法的缺点是,某个位置需要一段时间才能使用,准确性可能会很差。您的服务可能需要等待一段时间,直到达到可接受的准确度(位置准确度值可能是错误的,因此最好等待几个样本)。整个方法需要根据您所需的更新频率和精度要求进行调整。如果你需要非常频繁和准确的更新我怀疑举行唤醒锁定并保持GPS活着可能是唯一的方法。

我还尝试使用PendingIntent使用lm.requestLocationUpdates()。这确实唤醒了我的服务,并将其传递给了一个意图,但如果GPS在唤醒之前就已经睡了,那么意图缺少一个位置。