如何在后台运行locationlistener

时间:2015-02-16 16:56:16

标签: android background listener locationlistener

我想在我的应用程序上运行locationlistener,每隔10米或每5秒发送一个新的“弹出窗口”。稍后我会将我的数据发送到云端。

这是我的GPSTracker课程:

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // 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

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        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();
        }

        return location;
    }

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

        // 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();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {


    }

    @Override
    public void onProviderDisabled(String provider) {


    }

    @Override
    public void onProviderEnabled(String provider) {

        Toast.makeText(GPSTracker.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

对于我的活动类,我做了这个:

gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();

我收到数据,这是有效的。但现在我想在后台运行数据,所以当位置发生变化时,我可以实现一个将数据发送到云端的功能。

我试过了:

private void startGPSTrackerInBackground() {
    new AsyncTask<Void,Void,String>() {

        @Override
        protected String doInBackground(Void... params) {
            String msg = "This message runs in background";


            gps = new GPSTracker(MainActivity.this);

            if(!gps.canGetLocation()){
                gps.showSettingsAlert();
            }else{
                gps = new GPSTracker(MainActivity.this);
                double latitude2 = gps.getLatitude();
                double longitude2 = gps.getLongitude();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
        }
    }.execute(null, null, null);

}

但是在这个功能中,我不可能获得GPSTracker课程的信息,任何人都有可能做到这一点吗?

1 个答案:

答案 0 :(得分:1)

创建一个独立的类,添加一个GPSTracker成员变量并将其传递给构造函数。将您的任务包装在稍后可以调用的方法中:

public class BackgroundGPSTracker() {
    GPSTracker tracker;

    public BackgroundGPSTracker(GPSTracker tracker) {
        this.tracker = tracker;
    }

    public void run() {
        new AsyncTask<Void,Void,String>() {
            @Override
            protected String doInBackground(Void... params) {
                // Do some background stuff.
            }

            @Override
            protected void onPostExecute(String msg) {
                // Do after work stuff
            }
        }.execute(null, null, null);
    }
}

使用:

如果你像这样创建GPSTracker:

gps = new GPSTracker(MainActivity.this);

然后你开始将活动传递给任务:

BackgroundGPSTracker bgGPSTracker= new BackgroundGPSTracker(gps);
bgGPSTracker.run();

修改

使用成员变量存储上次已知位置,使用计时器来安排更新:

public class CampaignsDiscoverActivity extends Activity{
    static final int QUERY_CAMPAINGS_DELAY = 30000;// milliseconds

    Location currentLocation;

    Timer timer;

    void restartTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendDataToServerOrWhatever();
            }
        }, QUERY_CAMPAINGS_DELAY, QUERY_CAMPAINGS_DELAY);
    }

    void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    void sendDataToServerOrWhatever() {
        // Do some stuff using currentLocation
    }

为位置更改设置侦听器。当提升位置时,停止计时器,继续工作并重新启动它:

void startGPSUpdates() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            stopTimer();

            currentLocation = location;
            sendDataToServerOrWhatever();
        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    // Initialize location.
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (currentLocation == null) {
        currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    restartTimer();
}

启动系统只需调用startGPSUpdates

当应用程序转到后台时您应该暂停监听器,并在前台恢复时继续:

@Override
public void onPause() {
    super.onPause();

    if (applicationData.isLoggedIn()) {
        pauseLocationUpdates();
    }
}

@Override
public void onResume() {
    super.onResume();

    if (applicationData.isLoggedIn()) {
        resumeLocationUpdates();
    }
}

void pauseLocationUpdates() {
    locationManager.removeUpdates(locationListener);
}

void resumeLocationUpdates() {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

我认为你应该对计时器做同样的事情,但我使用它的应用程序还没有完成并经过全面测试,所以你可能会发现错误。

希望有所帮助。