Android上的多个Proximity警报无法正常工作

时间:2013-09-24 22:37:05

标签: java android gps

您好我正在尝试使用GPS追踪器查找位置,然后按下保存按钮以便在sharedPrefernces中保存位置并添加警报?该应用程序运行,但当我按下保存按钮它崩溃和'抱歉意外....'消息出现..任何帮助将非常感激

public class GPSTracker extends Service implements LocationListener{

//distance to update in meters and millisec's
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long  MIN_TIME_BW_UPDATES = 1000 * 60;


    //GPS & network status
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;



    //Declaring location Manager
    protected LocationManager locationManager;
    private Context mContext;

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

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

            //getting GPS & network status 
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled){
                //none enabled
            }
            else{
                this.canGetLocation = true;
                //first from network provider
                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();
                    }
                }
            }
        //Then use GPS service
            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;
}

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

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



//Alert message to turn on GPS

//check network provider
public boolean canGetLocation(){
    return this.canGetLocation;
}

//settings alert box
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
    alertDialog.setTitle("GPS is settings");
    //dialog message
    alertDialog.setMessage("GPS are 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();
        }
    });

    alertDialog.show();
}

//停止gps监听器     public void stopUsingGPS(){         if(locationManager!= null){             locationManager.removeUpdates(GPSTracker.this);         }     }

public class MainActivity extends Activity {

        protected LocationManager locationManager;

        double latitude =0;
        double longitude  =0;

         private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
         private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";



            private static final long POINT_RADIUS = 1000; // in Meters
            private static final long PROX_ALERT_EXPIRATION = -1;


            private static final String PROX_ALERT_INTENT = "com.example.Shared.ProximityAlert";

        GPSTracker gps;
        Location location;

        private static final NumberFormat nf = new DecimalFormat("##.########");

        private EditText latitudeEditText;
        private EditText longitudeEditText;
        private Button findCoordinatesButton;
        private Button savePointButton;

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            latitudeEditText = (EditText) findViewById(R.id.point_latitude);
            longitudeEditText = (EditText) findViewById(R.id.point_longitude);
            findCoordinatesButton = (Button) findViewById(R.id.find_coordinates_button);
            savePointButton = (Button) findViewById(R.id.save_point_button);

            findCoordinatesButton.setOnClickListener(new OnClickListener() {           

                @Override
                public void onClick(View v) {
                    // create class object
                    gps = new GPSTracker(MainActivity.this);

                    // check if GPS enabled    
                    if(gps.canGetLocation()){                            
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();                      
                        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();   

                        latitudeEditText.setText(nf.format(gps.getLatitude()));
                        longitudeEditText.setText(nf.format(gps.getLongitude()));

                    }else{
                        gps.showSettingsAlert();
                    }
                }
            });

            savePointButton.setOnClickListener(new OnClickListener() {           
                @Override
                public void onClick(View v) {

                        saveCoordinatesInPreferences(((float)gps.getLatitude()),((float)gps.getLongitude()));
                        addProximityAlert(gps.getLatitude(), gps.getLongitude());
                        Toast.makeText(getApplicationContext(), "Alert Paced on - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

                }
            });         
        }         

        void addProximityAlert(double latitude, double longitude) {             

            Intent intent = new Intent(PROX_ALERT_INTENT);
            PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

            locationManager.addProximityAlert(latitude, longitude,  POINT_RADIUS, PROX_ALERT_EXPIRATION,proximityIntent);

           IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT); 
           registerReceiver(new ProximityIntentReceiver(), filter);

           Log.d("Alert", "Proximity Alert Added");

        }


        void saveCoordinatesInPreferences(float latitude, float longitude) {
            SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = prefs.edit();
            prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
            prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
            prefsEditor.commit();
        }

        Location retrievelocationFromPreferences() {
            SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
            Location location = new Location("POINT_LOCATION");
            location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY, 0));
            location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY, 0));
            return location;
        }

和出现的错误

09-25 17:44:35.712: E/AndroidRuntime(16340): FATAL EXCEPTION: main
09-25 17:44:35.712: E/AndroidRuntime(16340): java.lang.NullPointerException
09-25 17:44:35.712: E/AndroidRuntime(16340):    at    android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at     com.project.shared2.MainActivity.retrievelocationFromPreferences(MainActivity.java:119)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at            com.project.shared2.GPSTracker.onLocationChanged(GPSTracker.java:152)
09-25 17:44:35.712: E/AndroidRuntime(16340):    at     android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:227)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at    android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:160)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at      android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:176)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at      android.os.Handler.dispatchMessage(Handler.java:99)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at      android.os.Looper.loop(Looper.java:123)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at android.app.ActivityThread.main(ActivityThread.java:3691)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at java.lang.reflect.Method.invokeNative(Native Method)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at java.lang.reflect.Method.invoke(Method.java:507)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
09-25 17:44:35.712: E/AndroidRuntime(16340):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
 09-25 17:44:35.712: E/AndroidRuntime(16340):   at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案