没有得到经纬度android中每1分钟后, [英] Not getting Latitude and longitude after every 1 minute in android

查看:319
本文介绍了没有得到经纬度android中每1分钟后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这一个Android程序,我得到的纬度经度吐司各1分钟间隔后,人口土司甚至经过我的应用程序关闭。

我下面试过,但我只获得时间的纬度和经度,请告诉我,我应该怎么做它来获得持续纬度长toast.My code是如下:
GPStracker.java

 包com.epe.trucktrackers;进口java.util.Timer中;
进口java.util.TimerTask中;进口utils.Const;
进口android.app.AlertDialog;
进口android.app.Service;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;
进口android.os.IBinder;
进口android.provider.Settings;
进口android.util.Log;
进口android.widget.Toast;公共类GPSTracker扩展服务实现LocationListener的{    私人最终上下文mContext;    //标志GPS状态
    布尔isGPSEnabled = FALSE;    //标志网络状态
    布尔isNetworkEnabled = FALSE;
    //标志GPS状态
    布尔canGetLocation = FALSE;
    私人定时器定时器;
    私人更新周期长;
    公共静态最后弦乐存根= NULL;
    的LocationManager mlocmag;
    LocationListener的mlocList;
    私人双重纬度,longn;    地点位置; // 位置
    双纬度; //纬度
    双经度; //经度    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; //10米    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟    //声明一个位置管理
    受保护的LocationManager的LocationManager;    公共GPSTracker(上下文的背景下){
        this.mContext =背景;
        的getLocation();
    }    公共场所的getLocation(){
        尝试{
            的LocationManager =(的LocationManager)mContext
                    .getSystemService(LOCATION_SERVICE);            //获取GPS状态
            isGPSEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);            //获取网络状态
            isNetworkEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);            如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
                //没有启用网络供应商
            }其他{
                this.canGetLocation = TRUE;
                如果(isNetworkEnabled){
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(网络,网络);
                    如果(的LocationManager!= NULL){
                        位置=的LocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        如果(位置!= NULL){
                            纬度= location.getLatitude();
                            经度= location.getLongitude();
                        }
                    }
                }
                //如果GPS功能的获得纬度/长期使用GPS服务
                如果(isGPSEnabled){
                    如果(位置== NULL){
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                        Log.d(GPS已启用,GPS功能的);
                        如果(的LocationManager!= NULL){
                            位置=的LocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            如果(位置!= NULL){
                                纬度= location.getLatitude();
                                经度= location.getLongitude();
                            }
                        }
                    }
                }
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回的位置;
    }    / **
     *停止使用GPS监听器调用该函数将停止使用您的GPS
     *应用
     * * /
    公共无效stopUsingGPS(){
        如果(的LocationManager!= NULL){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }    / **
     *函数来获取纬度
     * * /
    公共双getLatitude(){
        如果(位置!= NULL){
            纬度= location.getLatitude();
        }        //返回纬度
        返回纬度;
    }    / **
     *函数来获取经度
     * * /
    公共双getLongitude(){
        如果(位置!= NULL){
            经度= location.getLongitude();
        }        //返回经度
        返回经度;
    }    / **
     *功能检查启用GPS / WIFI
     *
     * @返回布尔
     * * /
    公共布尔canGetLocation(){
        返回this.canGetLocation;
    }    / **
     *功能,以显示设置警告对话框在pressing设置按钮会
     *劳克设置选项
     * * /
    公共无效showSettingsAlert(){
        AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext);        //设置对话框标题
        alertDialog.setTitle(GPS是设置);        //设置对话框留言
        alertDialog
                .setMessage(GPS未启用你想要去设置菜单?);        //在pressing设置按钮
        alertDialog.setPositiveButton(设置,
                新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话,诠释它){
                        意向意图=新意图(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(意向);
                    }
                });        //在pressing取消按钮
        alertDialog.setNegativeButton(取消,
                新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话,诠释它){
                        dialog.cancel();
                    }
                });        //显示警报信息
        alertDialog.show();
    }    @覆盖
    公共无效onLocationChanged(地点){        字符串消息=的String.format(
                位置\\ n经度:%1 $ S \\北纬:%2 $ S
                location.getLongitude(),location.getLatitude());
        的System.out.println(氦氖:::::::::::多头纬度............ !!!+消息);
        经度= location.getLongitude();
        纬度= location.getLatitude();
        Toast.makeText(mContext,纬度++经度,Toast.LENGTH_LONG)
                。显示();
        / * UpdateWithNewLocation(位置); * /
        的System.out.println(:位置CHANE);
    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){
    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){
    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        返回null;
    }}

Activity.java

 包com.epe.trucktrackers;进口org.json.JSONException;
进口org.json.JSONObject;进口utils.Const;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.Intent;
进口android.location.Location;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.telephony.TelephonyManager;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;
进口backend.BackendAPIService;公共类MainActivity延伸活动{
    的EditText et_registration_no;
    按钮btn_register;
    静态GPSTracker GPS ;;
    串纬度,经度;
    私人ProgressDialog pDialog;
    串UDID;
    字符串状态;
    串TRACKING_ID;
    串UDID;
    串LATI;
    串隆基;
    串registration_no;
    INT标志;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        et_registration_no =(EditText上)findViewById(R.id.et_truck_no);
        btn_register =(按钮)findViewById(R.id.btn_reg);        TelephonyManager TelephonyMgr =(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        UDID = TelephonyMgr.getDeviceId();
        GPS =新GPSTracker(MainActivity.this);        btn_register.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                GPS =新GPSTracker(MainActivity.this);
                如果(gps.canGetLocation()){                    双纬度= gps.getLatitude();
                    双经度= gps.getLongitude();                    // \\ n是新行
                    Toast.makeText(
                            getApplicationContext(),
                            您现在的位置是 - \\ nLat:+纬度
                                    +\\ nLong:+经度,Toast.LENGTH_LONG)
                            。显示();
                    纬度北纬= +;
                    LNG =经度+;                }其他{
                    //无法获取位置
                    未启用// GPS或网络
                    //要求用户在设置中启用GPS /网络
                    gps.showSettingsAlert();
                }
                新RegistartionApi()执行();                System.out的
                        .println(::::::::::::::服务启动:::::::::::::);
            }
        });        // API调用的REGISTARTION .. !!    }    类RegistartionApi扩展的AsyncTask<太虚,太虚,太虚> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            //显示进度对话框
            pDialog =新ProgressDialog(MainActivity.this);
            pDialog.setMessage(请稍候...);
            pDialog.setCancelable(假);
            pDialog.show();
            System.out的
                    .println(==========里面preexecute ===================);        }        @覆盖
        保护无效doInBackground(虚空......为arg0){
            字符串registrationURL = Const.API_REGISTRATION +?UDID =+ UDID
                    +与&纬度=+纬度+与&经度=+经度
                    +与& registration_no =
                    + et_registration_no.getText()的toString()修剪()。
            registrationURL = registrationURL.replace(,%);            BackendAPIService SH =新BackendAPIService();
            的System.out.println(:::::::::::::注册URL :::::::::::;
                    + registrationURL);
            字符串jsonStr = sh.makeServiceCall(registrationURL,
                    BackendAPIService.POST);            Log.d(回应:,>中+ jsonStr);
            的System.out.println(=============我的反应==========+ jsonStr);            如果(jsonStr!= NULL){
                尝试{
                    JSONObject的jsonObj =新的JSONObject(jsonStr);
                    JSONObject的C =新的JSONObject(jsonStr);                    如果(jsonObj.has(身份)){
                        状态= jsonObj.getString(状态);
                        {
                            如果(status.equalsIgnoreCase(成功)){
                                标志= 1;
                                C = jsonObj.getJSONObject(truck_tracking);
                                TRACKING_ID = c.getString(TRACKING_ID);
                                UDID = c.getString(UDID);
                                拉提= c.getString(纬度);
                                茇= c.getString(经度);
                                registration_no = C
                                        .getString(registration_no);                            }其他{
                                标志= 2;
                                Toast.makeText(MainActivity.this,失败,
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }其他{
                Log.e(的ServiceHandler,无法从URL得到任何数据);
            }            返回null;
        }        @覆盖
        保护无效onPostExecute(虚空结果){
            super.onPostExecute(结果);
            //辞退进度对话框
            如果(pDialog.isShowing())
                pDialog.dismiss();
            如果(标志== 1){
                Toast.makeText(MainActivity.this,登记完成,
                        Toast.LENGTH_SHORT).show();
                / *意向书I =新意图(getApplicationContext(),GPSTracker.class);
                startService(ⅰ); * /            }        }
    }}


解决方案

试试这个。
    包com.sample.location;

 进口java.util.Timer中;
进口java.util.TimerTask中;进口android.content.Context;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;
公共类MyLocation {
    定时器定时器1;
    LM的LocationManager;
    LocationResult locationResult;
    布尔gps_enabled = FALSE;
    布尔network_enabled = FALSE;    公共布尔的getLocation(上下文的背景下,LocationResult结果){
        //我用LocationResult回调类从传递位置值
        // MyLocation用户code。
        locationResult =结果;
        如果(LM == NULL)
            LM =(的LocationManager)上下文
            .getSystemService(Context.LOCATION_SERVICE);        //如果供应商是不允许的异常将被抛出。
        尝试{
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }赶上(例外前){
        }
        尝试{
            network_enabled = LM
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }赶上(例外前){
        }        //如果没有启用提供商不启动监听器
        如果(gps_enabled&安培;!&安培;!network_enabled)
            返回false;        如果(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,
                    locationListenerGps);
        如果(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,
                    locationListenerNetwork);
        定时器1 =新的Timer();
        timer1.schedule(新GetLastLocation(),60 * 1000);
        返回true;
    }    LocationListener的locationListenerGps =新LocationListener的(){
        @覆盖
        公共无效onLocationChanged(地点){
            timer1.cancel();
            locationResult.gotLocation(位置);
            lm.removeUpdates(本);
            lm.removeUpdates(locationListenerNetwork);
        }        / **
         *当提供由用户禁用调用。如果requestLocationUpdates叫上一个已经禁用的提供者,这种方法被立即调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * /
        @覆盖
        公共无效onProviderDisabled(字符串提供商){
        }
        / **
         *当提供由用户启用时调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * /
        @覆盖
        公共无效onProviderEnabled(字符串提供商){
        }
        / **
         *当调用的供应商的地位变化。当提供者无法获取的位置,或者如果提供者在一段不可用的后最近变得可用此方法被调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * @参数状态
         * OUT_OF_SERVICE如果供应商停止服务,而这预计不会在不久的将来改变; TEMPORARILY_UNAVAILABLE如果提供者暂时不可用,但预计将很快上市;和可用如果提供当前可用。
         * @参数演员
         *可选包将包含提供商特定的状态变量。
                许多的额外捆绑共同键/值对下面列出。使用任何键的这个名单上的供应商必须按如下所述提供相应的值。
                卫星 - 卫星的数量用于派生修复
         * /
        @覆盖
        公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
        }
    };    LocationListener的locationListenerNetwork =新LocationListener的(){
        / **
         *当位置改变时调用。
         *有关于使用所提供的定位对象没有限制。
         * @参数位置
         *新的位置,作为一个Location对象。
         * /
        @覆盖
        公共无效onLocationChanged(地点){
            timer1.cancel();
            locationResult.gotLocation(位置);
            lm.removeUpdates(本);
            lm.removeUpdates(locationListenerGps);
        }
        / **
         *当提供由用户禁用调用。如果requestLocationUpdates叫上一个已经禁用的提供者,这种方法被立即调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * /
        @覆盖
        公共无效onProviderDisabled(字符串提供商){
        }
        / **
         *当提供由用户启用时调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * /
        @覆盖
        公共无效onProviderEnabled(字符串提供商){
        }
        / **
         *当调用的供应商的地位变化。当提供者无法获取的位置,或者如果提供者在一段不可用的后最近变得可用此方法被调用。
         * @参数提供商
         *与此更新相关的位置提供者的名称。
         * @参数状态
         * OUT_OF_SERVICE如果供应商停止服务,而这预计不会在不久的将来改变; TEMPORARILY_UNAVAILABLE如果提供者暂时不可用,但预计将很快上市;和可用如果提供当前可用。
         * @参数演员
         *可选包将包含提供商特定的状态变量。
                许多的额外捆绑共同键/值对下面列出。使用任何键的这个名单上的供应商必须按如下所述提供相应的值。
                卫星 - 卫星的数量用于派生修复
         * /
        @覆盖
        公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
        }
    };    / **
     *要计算的GPS位置和网络位置
     *每5秒这个类的帮助
     *
     * /
    类GetLastLocation扩展的TimerTask {
        @覆盖
        公共无效的run(){
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);            位置net_loc = NULL,gps_loc = NULL;
            如果(gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            如果(network_enabled)
                net_loc = LM
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);            //如果有两个值,用最新一期
            如果(gps_loc = NULL&放大器;!&安培;!net_loc = NULL){
                如果(gps_loc.getTime()> net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                其他
                    locationResult.gotLocation(net_loc);
                返回;
            }            如果(gps_loc!= NULL){
                locationResult.gotLocation(gps_loc);
                返回;
            }
            如果(net_loc!= NULL){
                locationResult.gotLocation(net_loc);
                返回;
            }
            locationResult.gotLocation(NULL);
        }
    }    / **
     *此抽象类用于从其他类中的位置。
     *
     * /
    公共静态抽象类LocationResult {
        公共抽象无效gotLocation(位置定位);
    }}

在您的Activity.java

 的LocationManager myLocationManager =(的LocationManager)getApplicationContext()getSystemService(Context.LOCATION_SERVICE)。
MyLocation myLocation =新MyLocation();
myLocation.getLocation(getApplicationContext(),locationResult);
    LocationResult locationResult =新LocationResult(){        @覆盖
        公共无效gotLocation(地点){
            双纬度= location.getLatitude();
            双经度= location.getLongitude();
}
};

I want to make an android program in that I get latitude and longitude in Toast after each 1 minute interval and populated on toast even after my application closed.

I have tried as below,But I only getting on time latitude and longitude,Please tell me what should i do for it to get continuously lat long in toast.My code is as below: GPStracker.java

package com.epe.trucktrackers;

import java.util.Timer;
import java.util.TimerTask;

import utils.Const;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    private Timer timer;
    private long UPDATE_INTERVAL;
    public static final String Stub = null;
    LocationManager mlocmag;
    LocationListener mlocList;
    private double lat, longn;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

        String message = String.format(
                "Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());
        System.out.println(":::::::::::Ne lat longs............!!!" + message);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        Toast.makeText(mContext, latitude + " " + longitude, Toast.LENGTH_LONG)
                .show();
        /* UpdateWithNewLocation(location); */
        System.out.println(":Location chane");
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

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

}

Activity.java

package com.epe.trucktrackers;

import org.json.JSONException;
import org.json.JSONObject;

import utils.Const;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import backend.BackendAPIService;

public class MainActivity extends Activity {
    EditText et_registration_no;
    Button btn_register;
    static GPSTracker gps;;
    String lat, lng;
    private ProgressDialog pDialog;
    String udid;
    String status;
    String tracking_id;
    String UDID;
    String lati;
    String longi;
    String registration_no;
    int flag;

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

        et_registration_no = (EditText) findViewById(R.id.et_truck_no);
        btn_register = (Button) findViewById(R.id.btn_reg);

        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        udid = TelephonyMgr.getDeviceId();
        gps = new GPSTracker(MainActivity.this);

        btn_register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                gps = new GPSTracker(MainActivity.this);
                if (gps.canGetLocation()) {

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

                    // \n is for new line
                    Toast.makeText(
                            getApplicationContext(),
                            "Your Location is - \nLat: " + latitude
                                    + "\nLong: " + longitude, Toast.LENGTH_LONG)
                            .show();
                    lat = latitude + "";
                    lng = longitude + "";

                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
                new RegistartionApi().execute();

                System.out
                        .println("::::::::::::::service started:::::::::::::");
            }
        });

        // api call for the REGISTARTION ..!!

    }

    class RegistartionApi extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
            System.out
                    .println("==========inside preexecute===================");

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            String registrationURL = Const.API_REGISTRATION + "?UDID=" + udid
                    + "&latitude=" + lat + "&longitude=" + lng
                    + "&registration_no="
                    + et_registration_no.getText().toString().trim();
            registrationURL = registrationURL.replace(" ", "%");

            BackendAPIService sh = new BackendAPIService();
            System.out.println(":::::::::::::Registration url:::::::::::;"
                    + registrationURL);
            String jsonStr = sh.makeServiceCall(registrationURL,
                    BackendAPIService.POST);

            Log.d("Response: ", "> " + jsonStr);
            System.out.println("=============MY RESPONSE==========" + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONObject c = new JSONObject(jsonStr);

                    if (jsonObj.has("status")) {
                        status = jsonObj.getString("status");
                        {
                            if (status.equalsIgnoreCase("success")) {
                                flag = 1;
                                c = jsonObj.getJSONObject("truck_tracking");
                                tracking_id = c.getString("tracking_id");
                                UDID = c.getString("UDID");
                                lati = c.getString("latitude");
                                longi = c.getString("longitude");
                                registration_no = c
                                        .getString("registration_no");

                            } else {
                                flag = 2;
                                Toast.makeText(MainActivity.this, "Failed",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            if (flag == 1) {
                Toast.makeText(MainActivity.this, "Registration Done",
                        Toast.LENGTH_SHORT).show();
                /*Intent i = new Intent(getApplicationContext(), GPSTracker.class);
                startService(i);*/

            }

        }
    }

}

解决方案

Try this one. package com.sample.location;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    public boolean getLocation(Context context, LocationResult result) {
        // I use LocationResult callback class to pass location value from
        // MyLocation to user code.
        locationResult = result;
        if (lm == null)
            lm = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled)
            return false;

        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
        timer1 = new Timer();
        timer1.schedule(new GetLastLocation(), 60*1000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }

        /**
         * Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderDisabled(String provider) {
        }
        /**
         * Called when the provider is enabled by the user.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderEnabled(String provider) {
        }
        /**
         * Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
         * @param provider  
         *      the name of the location provider associated with this update. 
         * @param status  
         *      OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available. 
         * @param extras  
         *      an optional Bundle which will contain provider specific status variables. 
                A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below. 
                satellites - the number of satellites used to derive the fix 
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        /**
         * Called when the location has changed. 
         * There are no restrictions on the use of the supplied Location object.
         * @param location  
         *      The new location, as a Location object.  
         */
        @Override
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        /**
         * Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderDisabled(String provider) {
        }
        /**
         * Called when the provider is enabled by the user.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderEnabled(String provider) {
        }
        /**
         * Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
         * @param provider  
         *      the name of the location provider associated with this update. 
         * @param status  
         *      OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available. 
         * @param extras  
         *      an optional Bundle which will contain provider specific status variables. 
                A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below. 
                satellites - the number of satellites used to derive the fix 
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    /**
     * The GPS location and Network location to be calculated
     * in every 5 seconds with the help of this class  
     *
     */
    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc = null, gps_loc = null;
            if (gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (network_enabled)
                net_loc = lm
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // if there are both values use the latest one
            if (gps_loc != null && net_loc != null) {
                if (gps_loc.getTime() > net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if (gps_loc != null) {
                locationResult.gotLocation(gps_loc);
                return;
            }
            if (net_loc != null) {
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }

    /**
     * This abstract class is used to get the location from other class.
     *
     */
    public static abstract class LocationResult {
        public abstract void gotLocation(Location location);
    }

}

In your Activity.java

LocationManager myLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(getApplicationContext(), locationResult);


    LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {


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

这篇关于没有得到经纬度android中每1分钟后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆