如何添加和删除在位置管理多个感应警报 [英] How to add and remove multiple proximity alerts in location manager

查看:262
本文介绍了如何添加和删除在位置管理多个感应警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过赋予独特reques code到它的PendingIntent的位置监听器添加多个接近警报,但我无法得到我的地方设置的位置警报。和APP也崩溃了好几次,请大家帮忙

这是我的code

 公共类LocationTrackerService扩展服务实现LocationListener的{
            私有静态最后长半径= 1000; //在米
            私有静态最后长PROX_ALERT_EXPIRATION_TIME = -1;
            上下文语境;
            弦乐味精;
            的LocationManager的LocationManager;
            在米//;公众最终诠释MINIMUM_UPDATE_DISTANCE = 100
            公众最终诠释MINIMUM_UPDATE_INTERVAL = 30 * 1000; //以秒为单位
            公共静态字符串PROX_ALERT_INTENT =com.ginormous.transportmanagement.ProximityAlert;
            LocationAlertReceiver proximityAlertReceiver;
            私有静态最后的NumberFormat NF =新DecimalFormat的(## ########);
            IntentFilter的过滤器;
            ArrayList的< LocationModel> locationdata;            @覆盖
            公众诠释onStartCommand(意向意图,诠释标志诠释startId){
                // TODO自动生成方法存根
                上下文= getApplicationContext();
                getPickuppoints();
                registerIntents();                //将注册接收器
                registerReceiver();                Log.d(TAG,服务启动);
                返回START_STICKY;
            }
            @覆盖
            公众的IBinder onBind(意向意图){
                // TODO自动生成方法存根
                返回null;
            }
            私人无效registerIntents(){
                如果(locationdata =空&放大器;!&放大器; locationdata.size()大于0){
                    // TODO自动生成方法存根
                    对于(INT J = 0; J< locationdata.size(); J ++){
                        LocationModel OBJ = locationdata.get(J);
                        setProximityAlert(OBJ);
                    }
                }
            }            私人无效getPickuppoints(){
                光标CUR = NULL;
                Dbhelper DB =新Dbhelper(背景);
                SQLiteDatabase SQLDB = db.getReadableDatabase();
                尝试{
                    查询字符串= + Dbhelper.TBL_LATLONG从选择*;
                    CUR = sqldb.rawQuery(查询,NULL);
                    如果(cur.getCount()大于0){
                        locationdata =新的ArrayList< LocationModel>();
                        为(cur.moveToFirst();! cur.isAfterLast(); cur.moveToNext()){
                            locationdata.add(
                                    新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))));
                        }
                    }                }赶上(例外五){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
                cur.close();
                db.close();
                sqldb.close();
            }            @覆盖
            公共无效onLocationChanged(地点){
                尝试{
                    如果(的LocationManager!= NULL){
                        // TODO自动生成方法存根
                        串LATT = nf.format(location.getLatitude());
                        串茇= nf.format(location.getLongitude());                        Toast.makeText(上下文,LATT +:+茇,Toast.LENGTH_LONG).show();
                        Log.d(TAG,经纬度信息+ LATT +:+隆基);
                        / *位置pointLocation =新的位置(POINT_LOCATION);
                        pointLocation.setLatitude(latlongsFixed.get(指数));
                        pointLocation.setLongitude(77.36438);
                        浮距离= location.distanceTo(pointLocation);
                        Log.d(TAG,+距离); * /
                        // Toast.makeText(背景下,你是米您感兴趣的点了。
                        // Toast.LENGTH_LONG).show();
                        。Singelton.getInstance()setLastKnownLocation(位置);
                        如果(Utilities.checkInternetConnection(getApplicationContext())){
                            如果(Singelton.getInstance()。getRouteNumber()!= NULL)
                                sendLongLat(LATT,隆基);
                        }
                    }
                }赶上(例外五){
                    // TODO自动生成catch块
                    Toast.makeText(getApplicationContext(),Toast.LENGTH_LONG,在onLocationChanged()异常).show();
                    e.printStackTrace();
                }            }            @覆盖
            公共无效onProviderDisabled(字符串提供商){
                // TODO自动生成方法存根            }            @覆盖
            公共无效onProviderEnabled(字符串提供商){
                // TODO自动生成方法存根            }            @覆盖
            公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
                // TODO自动生成方法存根            }            @覆盖
            公共无效的onDestroy(){
                // TODO自动生成方法存根
                super.onDestroy();
                如果(的LocationManager!= NULL)
                    locationManager.removeUpdates(本);
                unregisterReceiver(proximityAlertReceiver);
            }            @覆盖
            公共布尔onUnbind(意向意图){
                // TODO自动生成方法存根
                返回super.onUnbind(意向);
            }            公共无效sendLongLat(最后弦乐latti,最后弦乐隆基){
                新的AsyncTask<弦乐,太虚,字符串>(){                    @覆盖
                    保护无效onPostExecute(字符串结果){
                        // TODO自动生成方法存根
                        super.onPostExecute(结果);
                        弦乐味精= NULL;
                        尝试{
                            JSONObject的JSON =新的JSONObject(结果);
                            字符串状态= json.getString(STATUS);
                            如果(status.equalsIgnoreCase(OK)){
                                味精=地点派;
                            }其他{
                                味精=出事了;
                            }
                            Toast.makeText(getApplicationContext(),味精,
                                    Toast.LENGTH_LONG).show();
                        }赶上(JSONException E){
                            // TODO自动生成catch块
                            e.printStackTrace();
                        }赶上(例外五){
                            // TODO:处理异常
                            e.printStackTrace();
                        }
                    }                    @覆盖
                    保护字符串doInBackground(字符串... PARAMS){
                        // TODO自动生成方法存根
                        ArrayList的<串GT;行=新的ArrayList<串GT;();
                        连接DB =新的Connection();
                        。字符串routeId = Singelton.getInstance()getRouteId();
                        如果(Utilities.checkInternetConnection(getApplicationContext())){
                            尝试{
                                线= db.putLatLong(putLatLong,2//路线ID
                                        ,隆基,latti);
                            }赶上(例外五){
                                // TODO自动生成catch块
                                e.printStackTrace();
                            }
                        }
                        返回lines.get(0);
                    }
                }。执行();
            }            私人无效setProximityAlert(LocationModel OBJ){
                的LocationManager =(的LocationManager)getSystemService(Context.LOCATION_SERVICE);
                如果(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                    AlertDialog.Builder建设者=新AlertDialog.Builder(背景);
                    builder.setTitle(GPS未启用); // GPS不能找到
                    builder.setMessage(请对您的设备的GPS开关); //要启用?
                    builder.setPositiveButton(设置,新DialogInterface.OnClickListener(){
                        公共无效的onClick(DialogInterface dialogInterface,int i)以{
                            context.startActivity(新意图(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    });
                    builder.setNegativeButton(OK,NULL);
                    builder.create()显示()。
                    返回;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        MINIMUM_UPDATE_INTERVAL,MINIMUM_UPDATE_DISTANCE,这一点);                意向意图=新意图(PROX_ALERT_INTENT + + obj.getPickupId(。)); //
                intent.putExtra(所在地,OBJ);
                的PendingIntent proximityIntent = PendingIntent.getBroadcast(背景下,的Integer.parseInt(obj.getPickupId())//唯一的ID /请求code
                        ,意向,PendingIntent.FLAG_CANCEL_CURRENT);
                locationManager.addProximityAlert(
                    obj.getLat(),//警报区域的中心点的纬度
                    obj.getLongi(),//警报区域的中心点的经度
                    RADIUS,//警报区域的中心点的半径,米
                    PROX_ALERT_EXPIRATION_TIME,//时间,这接近警戒,以毫秒为单位,或-1,指示没有到期
                    proximityIntent //将用来生成一个Intent火检测从警报区域进入或退出时
               );
                过滤器=新的IntentFilter(PROX_ALERT_INTENT);
            }            私人无效registerReceiver()
            {
                proximityAlertReceiver =新LocationAlertReceiver();
                registerReceiver(proximityAlertReceiver,过滤器);
            }        }

和近程预警接收器

 公共类LocationAlertReceiver扩展广播接收器{                私人INT NOTIFICATION_ID = 1000;
                公共静态字符串PROX_ALERT_INTENT =com.ginormous.transportmanagement.ProximityAlert;
                私人字符串UNIQUEID =;
                LocationModel locaObj;
                上下文语境;
                @覆盖
                公共无效的onReceive(上下文的背景下,意图意图){
                    // TODO自动生成方法存根\\
                    this.context =背景;
                    尝试{
                        LocationModel模型=((LocationModel)intent.getSerializableExtra(位置));
                        Toast.makeText(背景下,Proxmity警报接收器; ID:+ model.getPickupId()
                                Toast.LENGTH_SHORT).show();
                        removeProximityAlert(上下文,PROX_ALERT_INTENT ++ model.getPickupId()。);
                        Toast.makeText(上下文中,proxmity除去,1).show();
                    }赶上(例外五){
                        // TODO:处理异常
                        Toast.makeText(背景下,例外Proxmity警报接收器
                                Toast.LENGTH_SHORT).show();
                    }
                    /*if(intent.getExtras()。getSerializable(位置)!= NULL){
                        locaObj =(LocationModel)intent.getExtras()getSerializable(位置)。
                    }
                    字符串键= LocationManager.KEY_PROXIMITY_ENTERING;
                    布尔isEntering = intent.getBooleanExtra(KEY,FALSE);
                    如果(isEntering){
                            NotificationManager notificationManager =(NotificationManager)上下文
                                    .getSystemService(Context.NOTIFICATION_SERVICE);
                            意图int​​ent2 =新意图(背景下,MainLogin.class);
                            的PendingIntent的PendingIntent = PendingIntent.getActivity(
                                    上下文,0,intent2,PendingIntent.FLAG_CANCEL_CURRENT);
                            通知通知= createNotification();
                            notification.setLatestEventInfo(背景下,接近警报!
                                    位置:+ locaObj.getPickupName()+,的PendingIntent);
                            notificationManager.notify(NOTIFICATION_ID,通知);
                            Log.d(的getClass()getSimpleName(),输入。);                            removeProximityAlert(上下文,locaObj.getPickupId());                            //这将详细信息发送到服务器
                            如果(Utilities.checkInternetConnection(上下文))
                                新SendArrivalDetails()执行(locaObj.getPickupId());
                            其他
                                Utilities.sendArrivalDetails(上下文,locaObj.getPickupId(),N);
                    }
                    其他
                        Log.d(的getClass()getSimpleName(),退出。);
                * /                }
                私人无效removeProximityAlert(上下文的背景下,字符串uniqueid2){
                    // TODO自动生成方法存根
                    尝试{
                        的LocationManager的LocationManager =(的LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
                        意向意图=新意图(PROX_ALERT_INTENT + + uniqueid2。);
                        的PendingIntent的PendingIntent = PendingIntent.getBroadcast(上下文,的Integer.parseInt(uniqueid2),意图,0);
                        locationManager.removeProximityAlert(的PendingIntent);
                    }赶上(NumberFormatException的E){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }
                    赶上(例外五){
                        // TODO:处理异常
                        Toast.makeText(背景下,错误的去除promity警报+ uniqueid2,Toast.LENGTH_SHORT).show();
                    }
                }
                私人通知createNotification(){
                    通知通知=新的通知();                    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;                    返回通知;
                }                公共类SendArrivalDetails扩展的AsyncTask<弦乐,太虚,字符串> {
                    串pickupid =;
                    @覆盖
                    保护字符串doInBackground(字符串... PARAMS){
                        // TODO自动生成方法存根
                        ArrayList的<串GT;行=新的ArrayList<串GT;();
                        pickupid =参数[0];
                        尝试{
                            连接DB =新的Connection();
                            日历CAL = Calendar.getInstance();
                            SimpleDateFormat的SDF =新的SimpleDateFormat(YYYY-MM-DD HH:MM:SS);
                            db.saveArrivalDetails(savepickuptimer,pickupid,Singelton.getInstance()getAttType(),sdf.format(cal.getTime())。);
                        }赶上(例外五){
                            // TODO自动生成catch块
                            e.printStackTrace();
                        }
                        返回lines.get(0);
                    }                    @覆盖
                    保护无效onPostExecute(字符串结果){
                        // TODO自动生成方法存根
                        super.onPostExecute(结果);
                        尝试{
                            的JSONObject的JSONObject =新的JSONObject(结果);
                            字符串的响应= jsonObject.getString(STATUS);
                            如果(response.equals(STATUS)){
                                Utilities.sendArrivalDetails(上下文,pickupid,U);
                                Toast.makeText(背景下,近水楼台抵达详情派,1).show();
                            }
                        }赶上(例外五){
                            // TODO自动生成catch块
                            e.printStackTrace();
                            Toast.makeText(背景下,错误发送接近抵达详情,1).show();
                        }
                    }
                }            }

而在Menifest文件权限是

 <使用许可权的android:NAME =android.permission.ACCESS_FINE_LOCATION/>
    <使用许可权的android:NAME =android.permission.ACCESS_COARSE_LOCATION/>


解决方案

您必须保存所有接近的区域标识(要求code)和当u想删除这些区域只需要调用从的LocationManager删除。对于例如。

 意向意图=新的Intent();
        intent.setAction(AppConstants.BROAD_ACTION);
        的for(int i = 0; I< countRegionIDArr.size();我++){
            的PendingIntent的PendingIntent = PendingIntent.getBroadcast(AlertService.this,countRegionIDArr.get(I),意向,0);
            mlocManager.removeProximityAlert(的PendingIntent);
        }

I am trying to add multiple proximity alert in location listener by giving unique requesCode to its pendingIntent but I am unable to get the alert where I set the location. And app is also crashed several times, please help

here's my code

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

        }

And Proximity Alert receiver

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



            }

And permission in Menifest file are

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

解决方案

You have to save all proximity region IDs(request code) and when u want to remove these region just call to remove from locationmanager . For e.g.

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

这篇关于如何添加和删除在位置管理多个感应警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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