Java Android LocationManager:-显示进度对话框时出错

Java Android LocationManager:-显示进度对话框时出错,java,android,gps,locationmanager,Java,Android,Gps,Locationmanager,我正在开发一个需要获取用户当前位置的应用程序。我遵循本教程来实现我的目标。这个代码对我来说非常有效,但是在获取坐标时有一些延迟。在获取坐标之前,我想显示一个进度对话框 我在这里发现了一个类似的问题 但我不同意公认的答案。我试过了,但对我不起作用 我的问题是: 1.当应用程序首次启动时GPS设置为on时,ProgressDialog无限。也就是说,它不会拒绝 一旦找到位置坐标,应用程序就会崩溃 错误: 第二个问题是NullPointerException。不知何故,应用程序无法在主活动中找到对话框

我正在开发一个需要获取用户当前位置的应用程序。我遵循本教程来实现我的目标。这个代码对我来说非常有效,但是在获取坐标时有一些延迟。在获取坐标之前,我想显示一个进度对话框

我在这里发现了一个类似的问题

但我不同意公认的答案。我试过了,但对我不起作用

我的问题是: 1.当应用程序首次启动时GPS设置为on时,ProgressDialog无限。也就是说,它不会拒绝

  • 一旦找到位置坐标,应用程序就会崩溃
  • 错误: 第二个问题是NullPointerException。不知何故,应用程序无法在主活动中找到对话框。(内部onLocationChanged())

    请帮忙

    我的代码: 主要活动:-

    public class AndroidGPSTrackingActivity extends Activity {
    
        Button btnShowLocation;
    
        // GPSTracker class
        GPSTracker gps;
        ProgressDialog dialog;
        TextView tv_addressView;
        Location loc;
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            tv_addressView = (TextView)findViewById(R.id.tv_address);
            btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    
            // show location button click event
            btnShowLocation.setOnClickListener(new View.OnClickListener() {
    
        @Override
    public void onClick(View arg0) 
    {
    if(loc == null)
                        {
                                dialog = ProgressDialog.show(
    AndroidGPSTrackingActivity.this,
    "Getting Co-ordinates",
    "Please Wait ...");
                        }
    
                 });
        }
    
        @Override
        protected void onResume()
        {
            super.onResume();
            gps = new GPSTracker(getApplicationContext(),AndroidGPSTrackingActivity.this);
            loc = gps.getLocation();
            if(gps.canGetLocation())
             {
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                Log.d("Got","Lat = "+latitude+"\nLong = "+longitude);
             }
            else
            {
                        gps.showSettingsAlert();
            }
    
        }
    
        public void dismissDialog()
        {
            if(dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    
        public void upDateUI(String result)
        {
            tv_addressView.setText(result);
        }
    
    }
    
    GPSTracker.java

    public class GPSTracker extends Service implements LocationListener {
    
            ProgressDialog dialog;
        private final Context mContext;
    boolean isGPSEnabled = false;
        boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location; // location
        double latitude; // latitude
        double longitude; // longitude
    AndroidGPSTrackingActivity callingActivity;
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    protected LocationManager locationManager;
    
    
        public GPSTracker(Context context, AndroidGPSTrackingActivity activity) 
    {
            this.mContext = context;
                    this.callingActivity = activity;
                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;
        }
    
        public Location returnLocation()
        {
            return location;
        }
    
        /**
         * Stop using GPS listener
         * Calling this function will stop using GPS in your app
         * */
        public void stopUsingGPS(){
            if(locationManager != null){
                //dialog.dismiss();
                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(callingActivity);
    
            // 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);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    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) {
    
    
           callingActivity.dismissDialog();
    
        }
    
        @Override
        public void onProviderDisabled(String provider) {
            stopUsingGPS();
        }
    
        @Override
        public void onProviderEnabled(String provider) {
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
    }
    
    试试这个

    公共最终类GPSTracker实现LocationListener{

    private final Context mContext;
    
    // flag for GPS status
    public boolean isGPSEnabled = false;
    
    // flag for network status
    boolean isNetworkEnabled = false;
    
    // flag for GPS status
    boolean canGetLocation = false;
    
    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 = 1; // 10 meters
    
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
    
    // Declaring a Location Manager
    protected LocationManager locationManager;
    
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
    
    /**
     * Function to get the user's current location
     * 
     * @return
     */
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);
    
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            Log.v("isGPSEnabled", "=" + isGPSEnabled);
    
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
    
            if (isGPSEnabled == false && isNetworkEnabled == false) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    location=null;
                    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) {
                    location=null;
                    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) {
    }
    
    @Override
    public void onProviderDisabled(String provider) {
    }
    
    @Override
    public void onProviderEnabled(String provider) {
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    

    }

    为什么在
    GPSTracker
    类中扩展
    服务
    ?在
    mContext.startActivity(intent)之前行添加
    对话框。取消()在开始设置活动之前关闭警报@ρ∑ѕρєK:-我想这会在显示设置菜单之前关闭progressdialog。但是当应用程序启动时,请假设GPS已打开。在这种情况下,永远不会调用mContext.startActivity(intent)。在这种情况下,我应该将dialog.discouse()放在哪里,正如@ρцσρρѕρєK所指出的,您使用的教程代码有问题。GPSTracker是从服务派生的,但从未通过调用活动中的startService()启动。如果它确实需要作为服务运行,则需要进行更改。如果要将GPSTracker正确地实现为真正的服务,则在构造函数中传递活动并将其保存为成员是不安全的。该活动可能会在服务继续运行时被停止和销毁,给您留下一个无效的引用。@qbix:-太好了!!!完全有道理。。。请你给我指一下正确的方向好吗。一个教程将是伟大的!!!!下面还有一个我想试试的代码。但是再一次。。。该代码在当前形式下运行良好。问题是在显示ProgressDialog时。我的问题是ProgressDialog。我不知道我应该在哪里展示它,什么时候取消它。