首页 > 解决方案 > Android 应用程序中的后台位置更新。(用于实时位置跟踪)

问题描述

我正在开发一个位置跟踪应用程序。位置更新在前台运行良好。但在后台它通常不会获得位置更新。有时需要大约 10 分钟,有时甚至不更新。

我也尝试过使用该服务,但是当应用程序进入后台时它被杀死了。从 android 版本 8 我也无法从广播接收器重新启动服务。

我想在 5 秒间隔后获取位置更新(在前台和后台)


MyFusedLocationClass :

    public class MyFusedLocation {
    private static final String TAG = "MyFusedLocation";
    private static MyFusedLocation INSTANCE = null;
    FusedLocationProviderClient fusedLocationClient;
    PendingIntent locationUpdatePendingIntent;
    LocationRequest locationRequest;
    Context context;

    private MyFusedLocation(Context context) {
        this.context = context;
    }

    public static MyFusedLocation getINSTANCE(Context context) {
        if (INSTANCE == null) INSTANCE = new MyFusedLocation(context);
        return INSTANCE;
    }

    @SuppressLint("MissingPermission")
    public void initialize() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);

        locationRequest = LocationRequest.create();
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        Intent intent = new Intent(context, LocationUpdatesBroadcastReceiver.class);
        intent.setAction(LocationUpdatesBroadcastReceiver.ACTION_PROCESS_UPDATES);
        locationUpdatePendingIntent = PendingIntent.getBroadcast(context, 0, intent, 
        PendingIntent.FLAG_UPDATE_CURRENT);
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener((Activity) context, location -> {
                    if (location != null) {
                        setLocation(location);
                    }
                });
        startLocationUpdates();
    }

    private void setLocation(Location location) {
        AppPreference.INSTANCE.setCurrentLat(String.valueOf(location.getLatitude()));
        AppPreference.INSTANCE.setCurrentLong(String.valueOf(location.getLongitude()));
        Log.e("current_loc_lat", "" + location.getLatitude());
        Log.e("current_loc_log", "" + location.getLongitude());
    }

    @SuppressLint("MissingPermission")
    public void startLocationUpdates() {
        fusedLocationClient.requestLocationUpdates(locationRequest,
                locationUpdatePendingIntent);
    }
}
    

广播接收器类:

    public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver implements 
    INetworkEvent {
    public static final String ACTION_PROCESS_UPDATES =
            "com.three_ediots.younearme.action." + "PROCESS_UPDATES";
    public static final String TAG = "LocationBroadcast";
    Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        if (intent.getAction().equals(ACTION_PROCESS_UPDATES)) {
            LocationResult locationResult = LocationResult.extractResult(intent);

            if (locationResult != null) {
                Location location = locationResult.getLastLocation();
                AppPreference.INSTANCE.setCurrentLat(String.valueOf(location.getLatitude()));
              AppPreference.INSTANCE.setCurrentLong(String.valueOf(location.getLongitude()));
                              
                if (!AppPreference.INSTANCE.getUserToken().equals("")) {
                    Log.e(TAG, "api called");
                    hitShareLocationApi();
                }
            }
       }
    }
    private void hitShareLocationApi() {
        // API CODE
    }

    private void restartTimer() {
        Log.e(TAG, "restart timer");
        new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                Log.e(TAG, "Timer finished");
                hitShareLocationApi();
            }
        }.start();
    }

    @Override
    public void onNetworkCallInitiated(String service) {
        Log.e(TAG, "Ntw_Init_update_loc " + service);
    }

    @Override
    public void onNetworkCallCompleted(String service, String response) {
        Log.e(TAG, "Ntw_succ_update_loc " + service);
        Log.e(TAG, "Ntw_succ_update_loc " + response);
    }

    @Override
    public void onNetworkCallError(String service, String errorMessage) {
        restartTimer();   //In case of socket time or weak network
        Log.e(TAG, "Ntw_error_update_loc " + service);
        Log.e(TAG, "Ntw_error_message" + errorMessage);
    }
    }

标签: javaandroidbackgroundlocationupdates

解决方案


推荐阅读