没有接近警报“退出”即使我不在地区

时间:2015-02-10 00:30:03

标签: android broadcastreceiver android-service android-maps-v2 locationmanager

我创建了服务,每秒检查一次区域的接近程度。它开火了#34;进入该地区"正确。但是,当我离开地区时,它不断发出相同的信息"进入该地区" 。我在onLocationChanged()方法中添加了邻近度。

这是服务代码:

public class GPSTrackerService extends Service implements LocationListener {

    private Context mContext;
    LocationListener loc;
    // flag for GPS status
    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
    PendingIntent pendingIntent;
    private BroadcastReceiver mybroadcast;


    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters


    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    @Override
    public void onStart(Intent intent, int startid) {
        this.mContext=getBaseContext();
        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();
            Toast.makeText(this, "Proximity Service Stopped", Toast.LENGTH_LONG).show();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTrackerService.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?");


        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);
            }
        });


        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) {

        Toast.makeText(this, "loc changed", Toast.LENGTH_LONG).show();
        Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");                 
        pendingIntent= PendingIntent.getBroadcast(mContext, 0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
        locationManager.addProximityAlert(31.4668732, 74.2719786,  MIN_DISTANCE_CHANGE_FOR_UPDATES, -1, pendingIntent);             
        IntentFilter filter = new IntentFilter("in.wptrafficanalyzer.activity.proximity");  
        registerReceiver(new ProximityIntentReceiver(), filter);


    }

    @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;
    }

    @Override
    public void onDestroy() {
        try{
            unregisterReceiver(new ProximityIntentReceiver());
        }catch(IllegalArgumentException e){

        }
    }

}

这是我的用于触发通知/吐司的Broadcat接收器

 @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub


        boolean proximity_entering = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);

        if(proximity_entering){
            Toast.makeText(context,"Entering the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle="Proximity - Entry";
            notificationContent="Entered the region";
            tickerMessage = "Entered the region";
        }else{
            Toast.makeText(context,"Exiting the region"  ,Toast.LENGTH_LONG).show();


            notificationTitle="Proximity - Exit";
            notificationContent="Exited the region";
            tickerMessage = "Exited the region";

        }

        Intent notificationIntent = new Intent(context,NotificationView.class);
        notificationIntent.putExtra("content", notificationContent );


        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                            .setWhen(System.currentTimeMillis())
                            .setContentText(notificationContent)
                            .setContentTitle(notificationTitle)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setAutoCancel(true)
                            .setTicker(tickerMessage)
                            .setContentIntent(pendingIntent);                           



        nManager.notify(1, notification);


}

}

1 个答案:

答案 0 :(得分:0)

嗯,我不确定......

首先,我会尝试增加变量" MIN_DISTANCE_CHANGE_FOR_UPDATES"由于位置估计的近似性质,大于1的值(1表示1米,而不是10)(没有"民用"提供商可以给你最多1米的位置,甚至不是GPS)。

然后,我还会将用于添加Proximity Alert的代码从OnLocationChanged事件添加到onStart或仅触发一次的其他事件或方法,因为在您的情况下,每当您移动超过1米时OnLocationChanged就会触发在新创建的Proximity Alert中,您可以获得大量相同的Proximity Alerts。

我不知道这是否会解决您的问题,但您应该尝试一下,您的广播接收器代码和接近警报代码看起来不错......