融合的位置提供程序api在几个小时后停止发送位置更新

时间:2019-07-04 16:12:36

标签: android fusedlocationproviderapi foreground-service

尝试每5分钟更新一次位置以跟踪用户的位置。

尝试将优先级设置为PRIORITY_HIGH_ACCURACY,删除了setExpirationDuration并使用了前台服务

位置服务类别

public class ForegroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final String EXTRA_LATITUDE = "extra_latitude";
    public static final String ACTION_LOCATION_BROADCAST = ForegroundLocationService.class.getName() + "LocationBroadcast";
    public static final String EXTRA_LONGITUDE = "extra_longitude";
    private static final String TAG = ForegroundLocationService.class.getSimpleName();
    public static final int GPS_NOTIFICATION = 1;
    private static final int UPDATE_INTERVAL_IN_SECONDS = 60*5;
    private static final int LOCATION_INTERVAL = 5*60*1000;
    private static final int FASTEST_LOCATION_INTERVAL = 3*60*1000;

    private boolean isForeground = false;
    private GoogleApiClient googleApiClient;
    private PowerManager.WakeLock wakeLock;

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

        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isForeground) {
            Log.v(TAG, "Starting the " + this.getClass().getSimpleName());
            startForeground(ForegroundLocationService.GPS_NOTIFICATION,
                    notifyUserThatLocationServiceStarted());
            isForeground = true;
            googleApiClient.connect();
            wakeLock.acquire();
        }
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
    }

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

    @Override
    public void onDestroy() {
        Log.v(TAG, "Stopping the " + this.getClass().getSimpleName());
        stopForeground(true);
        isForeground = false;
        googleApiClient.disconnect();
        if (null != wakeLock && wakeLock.isHeld()) {
            wakeLock.release();
        }
        super.onDestroy();
    }

    private LocationRequest getLocationRequest() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(LOCATION_INTERVAL);
        locationRequest.setFastestInterval(FASTEST_LOCATION_INTERVAL);
        locationRequest.setMaxWaitTime(TimeUnit.SECONDS.toMillis(UPDATE_INTERVAL_IN_SECONDS));
        return locationRequest;
    }

    private Notification notifyUserThatLocationServiceStarted() {
        Intent notificationIntent = new Intent(this, SalesHome.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String NOTIFICATION_CHANNEL_ID = "com.healingpharma.sales_touch";
            String channelName = "My Background Service";
            NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
            chan.setLightColor(Color.BLUE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(chan);
            builder = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.small_icon)
                    .setContentTitle("Healing Pharma")
                    .setContentText("Location tracking")
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis());
        } else {
            builder = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.small_icon)
                    .setContentTitle("Healing Pharma")
                    .setContentText("Location tracking")
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis());
        }
        final Notification notification;
        notification = builder.build();
        return notification;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, getLocationRequest(), this);
        } catch (SecurityException securityException) {
            Log.e(TAG, "Exception while requesting location updates", securityException);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Google API Client suspended.");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(TAG, "Failed to connect to Google API Client.");
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.d(TAG, "== location != null");
            float acc = location.getAccuracy();
            // writing log with current time in txt file in external storage of the device.
            com.healingpharma.sales_touch.Constants.appendLog("Latitude : " + String.valueOf(location.getLatitude())+" Longitude : "+ String.valueOf(location.getLongitude()));
           
        if (acc <= 200) {
                sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
            }
        }
    }

    private void sendMessageToUI(String lat, String lng) {
        Log.d(TAG, "Sending info...");
        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra(EXTRA_LATITUDE, lat);
        intent.putExtra(EXTRA_LONGITUDE, lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

以下代码从“活动”请求位置更新服务

Intent intent = new Intent(this, ForegroundLocationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        this.getApplication().startForegroundService(intent);
} else {
       this.getApplication().startService(intent);
}

我正在设备中的txt文件中记录位置更新,但几个小时后它停止发送位置。

我在代码或任何解决方案中做什么错了?

0 个答案:

没有答案