【问题标题】:how to run locationlistener in background如何在后台运行locationlistener
【发布时间】:2015-02-16 16:56:15
【问题描述】:

我想在我的应用程序上运行一个位置监听器,它每 10m 或每 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 类的信息,有没有人想办法让这成为可能?

【问题讨论】:

    标签: android background listener locationlistener


    【解决方案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);
    }
    

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

    希望对您有所帮助。

    【讨论】:

    • 是什么意思?
    • 我编辑并改进了我的答案。请再次检查。
    • 谢谢,我现在有一个正在运行的后台函数,可以将我的数据发送到云端,但是我如何创建它,它只每 5 秒发送一次数据或在更改位置时发送数据?
    • 你可以使用这个函数的第二个和第三个参数:locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, , , locationListener);
    猜你喜欢
    • 1970-01-01
    • 2013-10-02
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多