如何在位置管理器中添加和删除多个邻近警报

时间:2014-07-01 08:30:49

标签: android broadcastreceiver locationlistener

我正在尝试通过向其pendingIntent提供唯一的requesCode来在位置侦听器中添加多个邻近警报,但是我无法获取设置位置的警报。并且应用程序也多次崩溃,请帮忙

这是我的代码

        public class LocationTrackerService extends Service implements LocationListener                       {
            private static final long RADIUS = 1000; // in Meters
            private static final long PROX_ALERT_EXPIRATION_TIME = -1;
            Context context;
            String msg;
            LocationManager locationManager;
            public final int MINIMUM_UPDATE_DISTANCE = 100;// in meters
            public final int MINIMUM_UPDATE_INTERVAL = 30 * 1000;// in seconds
            public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
            LocationAlertReceiver proximityAlertReceiver;
            private static final NumberFormat nf = new DecimalFormat("##.########");
            IntentFilter filter; 
            ArrayList<LocationModel> locationdata;

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
                // TODO Auto-generated method stub
                context = getApplicationContext();
                getPickuppoints();
                registerIntents();

                //will register receiver
                registerReceiver();

                Log.d("TAG", "service started");
                return START_STICKY;
            }
            @Override
            public IBinder onBind(Intent intent) {
                // TODO Auto-generated method stub
                return null;
            }


            private void registerIntents() {
                if (locationdata!=null && locationdata.size()>0) {
                    // TODO Auto-generated method stub
                    for (int j = 0; j < locationdata.size(); j++) {
                        LocationModel obj = locationdata.get(j);
                        setProximityAlert(obj);
                    }
                }
            }

            private void getPickuppoints(){
                Cursor cur=null;
                Dbhelper db=new Dbhelper(context);
                SQLiteDatabase sqldb=db.getReadableDatabase();
                try {
                    String query="select * from "+Dbhelper.TBL_LATLONG;
                    cur=sqldb.rawQuery(query, null);
                    if(cur.getCount()>0){
                        locationdata=new ArrayList<LocationModel>();
                        for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
                            locationdata.add(
                                    new LocationModel(
                                    cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUPID)),
                                    cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUP_NAME)),
                                    cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LATTITUDE)),
                                    cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LONGITUDE)),
                                    cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTEID)),
                                    cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTENUMBER))));
                        }
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                cur.close();
                db.close();
                sqldb.close();
            }

            @Override
            public void onLocationChanged(Location location) {
                try {
                    if (locationManager!=null) {
                        // TODO Auto-generated method stub
                        String latt = nf.format(location.getLatitude());
                        String longi= nf.format(location.getLongitude());

                        Toast.makeText(context, latt+" : "+longi, Toast.LENGTH_LONG).show();
                        Log.d("TAG", "latlong details" + latt+" : "+longi);
                        /*Location pointLocation = new Location("POINT_LOCATION");
                        pointLocation.setLatitude(latlongsFixed.get(index));
                        pointLocation.setLongitude(77.36438);
                        float distance = location.distanceTo(pointLocation);
                        Log.d("TAG", "" + distance);*/
                        //      Toast.makeText(context,"you are meters away from your point of interest.",
                        //              Toast.LENGTH_LONG).show();
                        Singelton.getInstance().setLastKnownLocation(location);
                        if (Utilities.checkInternetConnection(getApplicationContext())) {
                            if (Singelton.getInstance().getRouteNumber() != null)
                                sendLongLat(latt,longi);
                        }
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Exception in onLocationChanged()", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }

            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
                if(locationManager!=null)
                    locationManager.removeUpdates(this);
                unregisterReceiver(proximityAlertReceiver);
            }

            @Override
            public boolean onUnbind(Intent intent) {
                // TODO Auto-generated method stub
                return super.onUnbind(intent);
            }

            public void sendLongLat(final String latti, final String longi) {
                new AsyncTask<String, Void, String>() {

                    @Override
                    protected void onPostExecute(String result) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(result);
                        String msg = null;
                        try {
                            JSONObject json = new JSONObject(result);
                            String status = json.getString("STATUS");
                            if (status.equalsIgnoreCase("ok")) {
                                msg = "Location sent";
                            } else {
                                msg = "Something went wrong";
                            }
                            Toast.makeText(getApplicationContext(), msg,
                                    Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected String doInBackground(String... params) {
                        // TODO Auto-generated method stub
                        ArrayList<String> lines = new ArrayList<String>();
                        Connection db = new Connection();
                        String routeId = Singelton.getInstance().getRouteId();
                        if (Utilities.checkInternetConnection(getApplicationContext())) {
                            try {
                                lines = db.putLatLong("putLatLong", "2"// route id
                                        , longi, latti);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        return lines.get(0);
                    }
                }.execute();
            }

            private void setProximityAlert(LocationModel obj) { 
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("GPS not enabled");  // GPS not found
                    builder.setMessage("Please switch on the GPS of your device"); // Want to enable?
                    builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int i) {
                            context.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    });
                    builder.setNegativeButton("OK", null);
                    builder.create().show();
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        MINIMUM_UPDATE_INTERVAL, MINIMUM_UPDATE_DISTANCE, this);

                Intent intent = new Intent(PROX_ALERT_INTENT+"."+obj.getPickupId());//
                intent.putExtra("LOCATION", obj);
                PendingIntent proximityIntent = PendingIntent.getBroadcast(context, Integer.parseInt(obj.getPickupId())// unique id/request code
                        , intent, PendingIntent.FLAG_CANCEL_CURRENT);
                locationManager.addProximityAlert(
                    obj.getLat(), // the latitude of the central point of the alert region
                    obj.getLongi(), // the longitude of the central point of the alert region
                    RADIUS, // the radius of the central point of the alert region, in meters
                    PROX_ALERT_EXPIRATION_TIME, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration 
                    proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
               );
                filter = new IntentFilter(PROX_ALERT_INTENT);
            }

            private void registerReceiver()
            {
                proximityAlertReceiver=new LocationAlertReceiver();
                registerReceiver(proximityAlertReceiver, filter);
            }

        }

接近警报接收器

            public class LocationAlertReceiver extends BroadcastReceiver{

                private int NOTIFICATION_ID=1000;
                public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
                private String uniqueid="";
                LocationModel locaObj;
                Context context;
                @Override
                public void onReceive(Context context, Intent intent) {
                    // TODO Auto-generated method stub\
                    this.context=context;
                    try {
                        LocationModel model=((LocationModel) intent.getSerializableExtra("LOCATION"));
                        Toast.makeText(context, "Proxmity alert receiver; id : "+model.getPickupId(), 
                                Toast.LENGTH_SHORT).show();
                        removeProximityAlert(context, PROX_ALERT_INTENT+"."+model.getPickupId());
                        Toast.makeText(context, "proxmity removed", 1).show();
                    } catch (Exception e) {
                        // TODO: handle exception
                        Toast.makeText(context, "exception in Proxmity alert receiver", 
                                Toast.LENGTH_SHORT).show();
                    }


                    /*if(intent.getExtras().getSerializable("LOCATION")!=null){
                        locaObj=(LocationModel) intent.getExtras().getSerializable("LOCATION");
                    }
                    String KEY=LocationManager.KEY_PROXIMITY_ENTERING;
                    Boolean isEntering=intent.getBooleanExtra(KEY, false);
                    if(isEntering){
                            NotificationManager notificationManager = (NotificationManager) context
                                    .getSystemService(Context.NOTIFICATION_SERVICE);
                            Intent intent2 = new Intent(context, MainLogin.class);
                            PendingIntent pendingIntent = PendingIntent.getActivity(
                                    context, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
                            Notification notification = createNotification();
                            notification.setLatestEventInfo(context, "Proximity Alert!",
                                    "Location : "+locaObj.getPickupName()+",", pendingIntent);
                            notificationManager.notify(NOTIFICATION_ID, notification);
                            Log.d(getClass().getSimpleName(), "entering");

                            removeProximityAlert(context,locaObj.getPickupId());

                            //this will send the details to server
                            if(Utilities.checkInternetConnection(context))
                                new SendArrivalDetails().execute(locaObj.getPickupId());
                            else
                                Utilities.sendArrivalDetails(context, locaObj.getPickupId(),"N");
                    }
                    else
                        Log.d(getClass().getSimpleName(), "exiting");
                */  

                }
                private void removeProximityAlert(Context context,String uniqueid2) {
                    // TODO Auto-generated method stub
                    try {
                        LocationManager locationManager=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                        Intent intent=new Intent(PROX_ALERT_INTENT+"."+uniqueid2);
                        PendingIntent pendingIntent=PendingIntent.getBroadcast(context, Integer.parseInt(uniqueid2), intent, 0);
                        locationManager.removeProximityAlert(pendingIntent);
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        // TODO: handle exception
                        Toast.makeText(context, "error in removing promity alert for "+uniqueid2, Toast.LENGTH_SHORT).show();
                    }
                }
                private Notification createNotification() {
                    Notification notification = new Notification();

                    notification.icon = R.drawable.ic_launcher_transport;
                    notification.when = System.currentTimeMillis();

                    notification.flags |= Notification.FLAG_AUTO_CANCEL;
                    notification.flags |= Notification.FLAG_SHOW_LIGHTS;

                    notification.defaults |= Notification.DEFAULT_VIBRATE;
                    notification.defaults |= Notification.DEFAULT_LIGHTS;

                    notification.ledARGB = Color.WHITE;
                    notification.ledOnMS = 1500;
                    notification.ledOffMS = 1500;

                    return notification;
                }

                public class SendArrivalDetails extends AsyncTask<String, Void, String> {
                    String pickupid="";
                    @Override
                    protected String doInBackground(String... params) {
                        // TODO Auto-generated method stub
                        ArrayList<String> lines=new ArrayList<String>();
                        pickupid=params[0];
                        try {
                            Connection db=new Connection();
                            Calendar cal=Calendar.getInstance();
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            db.saveArrivalDetails("savepickuptimer", pickupid, Singelton.getInstance().getAttType(),sdf.format(cal.getTime()));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return lines.get(0);
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(result);
                        try {
                            JSONObject jsonObject=new JSONObject(result);
                            String response=jsonObject.getString("STATUS");
                            if(response.equals("STATUS")){
                                Utilities.sendArrivalDetails(context, pickupid,"U");
                                Toast.makeText(context, "proximity arrival details sent", 1).show();
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Toast.makeText(context, "error sending proximity arrival details", 1).show();
                        }
                    }
                }



            }

Menifest文件中的权限是

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

1 个答案:

答案 0 :(得分:5)

您必须保存所有邻近区域ID(请求代码),当您想删除这些区域时,只需调用从locationmanager中删除即可。例如,

Intent intent = new Intent();
        intent.setAction(AppConstants.BROAD_ACTION);
        for(int i=0;i<countRegionIDArr.size();i++){
            PendingIntent pendingIntent = PendingIntent.getBroadcast(AlertService.this, countRegionIDArr.get(i), intent, 0);
            mlocManager.removeProximityAlert(pendingIntent);
        }