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



我已经阅读了一些问题,并回答了Stackoverflow上的前景服务。他们说,这一前景总是在继续,从不被系统杀死。但是,当我在项目上实施并开始运行服务时,GPS图标就处于活动状态,然后关闭应用程序,然后一分钟GPS图标消失后。这意味着我的GPS不活动还是什么?之后,我重新打开了应用程序,并且GPS图标再次处于活动状态。

首先,我尝试从MainActivity上的startService更改为startForegroundService。但是,没有什么变化。如果我在项目上实现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秒发射到插座,所以我需要始终开启的前景服务。

使用 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
   }
}

最新更新