简体   繁体   English

具有多个POI的Android邻近警报

[英]Android Proximity alert with multiple POI

I have a database of lat and long with ID's and have retrieved this using json and want to apply the proximity alert to the geo locations in the array. 我有一个经纬度长且ID较长的数据库,并已使用json检索了此数据库,并希望将接近警报应用于数组中的地理位置。 I am unsure if the array is being passed properly or if the proximity alert.java is being invoked properly 我不确定是否正确传递了数组或是否正确调用了接近警报.java

This is the DB retrieval 这是数据库检索

public class retrieveDB extends AsyncTask<Void, Integer, Void> {

@Override
protected Void doInBackground(Void... params) {

    String result = "";
    InputStream is = null;

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://cs1.ucc.ie/~am32/getDB.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }
    catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());

    }
    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line);
            }
            is.close();
            result=sb.toString();

            Log.i("json string", result);
    }
    catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;

            System.out.println("Length"+ jArray.length());
            Log.d("DB","Length"+jArray.length());

            for(int i=0; i<jArray.length(); i++){

                    json_data = jArray.getJSONObject(i);
                    int id = json_data.getInt("ID") ;
                    //String title = json_data.getString("Title"); 
                    double latitude = json_data.getDouble("Lat"); 
                    double longitude = json_data.getDouble("Lon"); 

                    //Adds proximity to POI's
                    ProxAlert inst = new ProxAlert();
                    inst.addProximityAlert(latitude,longitude, id);
                    //
                    inst.saveCoordinatesInPreferences((float)latitude, (float)longitude);

                    //prints to logCat
                    System.out.println(id+"&"+latitude+"&"+longitude);


            }
    }
    catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
            Log.e("log_tag","Failed data as:\n"+result);
    }
        return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
    // invoked on UI thread publishProgress(Progress...).
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(Void result) {
    // result of background comp is passed to this step its invoked on the ui thread
    super.onPostExecute(result);

}

} }

and my Proximity Alert class 和我的接近警报类

public class ProxAlert extends Activity {

private static final long POINT_RADIUS = 10;
private static final long PROX_ALERT_EXPIRATION = -1;

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

private LocationManager locationManager;
private static final String PROX_ALERT_INTENT= "com.example.try0.ProximityIntentReceiver";

void addProximityAlert (double latitude, double longitude, int id){

    Bundle extras = new Bundle();
    extras.putInt("title", id);
    extras.putDouble("lat", latitude);
    extras.putDouble("lon", longitude);

    Intent intent = new Intent(PROX_ALERT_INTENT + id);
    //intent.putExtra("alert", "it works");
    intent.putExtra(PROX_ALERT_INTENT, extras);
    PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    //ProximityIntent will be used to generate an Intent to fire when entry to or exit from the alert region is detected
    locationManager.addProximityAlert(latitude,longitude,POINT_RADIUS,PROX_ALERT_EXPIRATION,proximityIntent);

    IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT + id);
    registerReceiver(new ProximityIntentReciever(), filter);

}

void saveCoordinatesInPreferences(float currentlatitude, float currentlongitude){
    SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putFloat(POINT_LATITUDE_KEY, currentlatitude);
    prefsEditor.putFloat(POINT_LONGITUDE_KEY, currentlongitude);
    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;
}

} }

I'd really appreciate some help its been a lot of staring and confusing 我真的很感谢一些帮助,它引起了很多关注和困惑

here is my service, this works perfectly, i know it does its on the market, just where the database is if you plug in your JSON maybe you can alter it to your needs 这是我的服务,效果很好,我知道它在市场上可以正常工作,只要插入JSON,数据库就在哪里,也许您可​​以根据需要进行更改

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


public class ProximityService extends Service{
    String proximitysd = "com.apps.ProximityService";
    int n = 0;
    private BroadcastReceiver mybroadcast;
    private LocationManager locationManager;
    MyLocationListener locationListenerp;
    public ProximityService() {


    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        mybroadcast = new ProximityIntentReceiver();
        locationManager = (LocationManager) 
                getSystemService(Context.LOCATION_SERVICE);





        double lat;
        double lng;
        float radius = 50f;
        long expiration = -1;
         MyDBAdapter db = new MyDBAdapter(this);
            Cursor cursor;
            db.read();
            cursor = db.getAllEntries();
            boolean go = cursor.moveToFirst();
            while(cursor.isAfterLast() != true){
                lat = cursor.getInt(MyDBAdapter.LATITUDE_COLUMN)/1E6;
                lng = cursor.getInt(MyDBAdapter.LONGITUDE_COLUMN)/1E6;
                String what = cursor.getString(MyDBAdapter.ICON_COLUMN);
                String how = cursor.getString(MyDBAdapter.FISH_COLUMN);
                String proximitys = "com.apps.ProximityService" + n;
                IntentFilter filter = new IntentFilter(proximitys);
                registerReceiver(mybroadcast, filter );

                Intent intent = new Intent(proximitys);

                intent.putExtra("alert", what);
                intent.putExtra("type", how);
                PendingIntent proximityIntent = PendingIntent.getBroadcast(this, n, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                locationManager.addProximityAlert(lat, lng, radius, expiration, proximityIntent);
                //sendBroadcast(new Intent(intent));

                n++;
                cursor.moveToNext();
            }
            db.close();
            cursor.close();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Proximity Service Stopped", Toast.LENGTH_LONG).show();
        try{
            unregisterReceiver(mybroadcast);
        }catch(IllegalArgumentException e){
            Log.d("reciever",e.toString());
        }


    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Proximity Service Started", Toast.LENGTH_LONG).show();
        //IntentFilter filter = new IntentFilter(proximitys);
        //registerReceiver(mybroadcast,filter);


    }
    public class ProximityIntentReceiver extends BroadcastReceiver{
         private static final int NOTIFICATION_ID = 1000;
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String key = LocationManager.KEY_PROXIMITY_ENTERING;

            Boolean entering = arg1.getBooleanExtra(key, false);
            String here = arg1.getExtras().getString("alert");
            String happy = arg1.getExtras().getString("type");



             NotificationManager notificationManager = 
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                    PendingIntent pendingIntent = PendingIntent.getActivity(arg0, 0, arg1, 0);        

                    Notification notification = createNotification();

                    notification.setLatestEventInfo(arg0, 
                        "Entering Proximity!", "You are approaching a " + here + " marker.", pendingIntent);

                    notificationManager.notify(NOTIFICATION_ID, notification);


                }

                private Notification createNotification() {
                    Notification notification = new Notification();

                    notification.icon = R.drawable.icon;
                    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;
                }
            //make actions



    }
     public class MyLocationListener implements LocationListener {
            public void onLocationChanged(Location location) {
                Toast.makeText(getApplicationContext(), "I was here", Toast.LENGTH_LONG).show();
            }

            public void onProviderDisabled(String s) {
            }
            public void onProviderEnabled(String s) {            
            }
            @Override
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }
        }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM