运行后台服务一分钟后,工具栏上的GPS图标消失了

时间:2019-05-14 05:41:33

标签: android gps foreground

我在Stackoverflow上阅读了一些有关前台服务的问题和答案。他们说,前景永远存在,永远不会被系统杀死。但是,当我在项目上实现并开始运行服务时,GPS图标处于活动状态,我关闭了该应用程序,一分钟后GPS图标消失了。这是否意味着我的GPS未处于活动状态?之后,我重新打开该应用程序,GPS图标再次处于活动状态。

首先,我尝试将startService上的startForegroundService更改为MainActivity。但是,没有任何变化。 如果我在项目中实现了WakeLock,那值得吗?

public class LocationService extends Service {
    private final LocationServiceBinder binder = new LocationServiceBinder();
    private final String TAG = LocationService.class.getSimpleName();
    private LocationListener mLocationListener;
    private LocationManager mLocationManager;

    public Socket mSocket;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SocketApplication application = (SocketApplication) getApplication();
        mSocket = application.getSocket();
        mSocket.connect();

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        startForeground(12345678, getNotification());
    }

    private class LocationListener implements android.location.LocationListener {
        private final String TAG = "LocationListener";
        private Location mLastLocation;

        public LocationListener(String provider)
        {
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            mLastLocation = location;
            latitude = mLastLocation.getLatitude();
            longitude = mLastLocation.getLongitude();
            bearing = mLastLocation.getBearing();
            speed = mLastLocation.getSpeed();

            try {
                javaToJson();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
            Toast.makeText(getApplicationContext(), "Please turn on your GPS Location", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    private void javaToJson() throws JSONException {
        mSocket.emit("incoming", jsonFinal);
        Log.i(TAG, jsonFinal);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationManager != null) {
            try {
                mLocationManager.removeUpdates(mLocationListener);
            } catch (Exception ex) {
                Log.i(TAG, "fail to remove location listeners, ignore", ex);
            }
        }
    }

    private void initializeLocationManager() {
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    public void startTracking() {
        initializeLocationManager();
        mLocationListener = new LocationListener(LocationManager.GPS_PROVIDER);

        try {
            int LOCATION_INTERVAL = 1000;
            long LOCATION_DISTANCE = 1;
            mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListener );

        } catch (java.lang.SecurityException ignored) {

        } catch (IllegalArgumentException ignored) {

        }

    }

    public void stopTracking() {
        this.onDestroy();
        mSocket.disconnect();
    }

    private Notification getNotification() {

        NotificationChannel channel = new NotificationChannel("channel_01", "My Channel", NotificationManager.IMPORTANCE_DEFAULT);

        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }

        Notification.Builder builder = new Notification.Builder(getApplicationContext(), "channel_01").setAutoCancel(true);
        return builder.build();
    }


    public class LocationServiceBinder extends Binder {
        public LocationService getService() {
            return LocationService.this;
        }
    }

}

因为该项目需要每5秒钟向套接字发送一次,所以我需要始终启用前台服务。

1 个答案:

答案 0 :(得分:0)

使用 ScheduledExecutorService

ScheduledExecutorService scheduleTaskExecutor ;



@Override
public int onStartCommand(Intent intent, int flags, int startId) {

     if (scheduleTaskExecutor == null) {
        scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
        //every 5 second execution
        scheduleTaskExecutor.scheduleAtFixedRate(new fivesec(), 0, 5, TimeUnit.SECONDS);

    }
    return START_STICKY;
}

然后:

 private class fivesec implements Runnable {
    public void run() {
      //all code that needs to be executed every five seconds
   }

}