Pregunta

En mi aplicación Oncreate, verifico algunas condiciones y luego comienzo una actividad como esta:

Intent startIntent = new Intent(getApplicationContext(), EnableLocationProviderActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(startIntent);

De esa actividad Comienzo un intentador que registre algunos oyentes para los sensores, se inicia como el significado pegajoso, debe detenerse explícitamente. Ese intentservice supervisa los sensores.

Mi problema es que cuando vuelvo a la primera actividad, los sensores ya no se detectan (puse un log.V en OnsensSorChanged (el inicio de datos que muestra, y luego se detiene).

¿Por qué podría ser que se detenga si no lo detuve explícitamente? Además, a veces que a veces se llama Ondetroy del intentismo, pero nuevamente, ¿cómo puede ser llamado si es pegajoso y no llamé de parada () y no se detuvo de otra manera?

¡Gracias! Guillermo.

editar

Este es el código del intentservice (que debería ejecutarse todo el tiempo, a pesar de que si el teléfono celular se va a dormir o se presiona el botón de inicio (conozco la batería y todo lo demás, el usuario será advertido sobre esto y lo hará Tener la oportunidad de cerrar la aplicación cuando quiera.

Se llama al servicio de la principal atención como esta:

Intent startIntent = new Intent(GdpTesisApplication.getInstance().getApplicationContext(), SensingService.class);
startService(startIntent);

y el código de servicio es este:

public class SensingService extends IntentService implements SensorEventListener {
    private float[] mAccelerationValues;
    private SensorManager mSensorManager = null;
    String sensorType = "";

    public SensingService(String name) {
        super(name);
        setIntentRedelivery(true);
    }

    public SensingService() {
        super("SensingService");
        setIntentRedelivery(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(ApplicationName,"SensingService.onStartCommand");
        super.onStartCommand(intent, flags, startId); // If this is not written then onHandleIntent is not called.
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(ApplicationName, "SensingService.onCreate");
        initialize();
    }

    private void initialize() {
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // This must be in onCreate since it needs the Context to be created.
        mAccelerationValues = new float[3];

        Log.v(ApplicationName, "Opening Location Service from Sensing Service");
        LocationService myLocation = new LocationService();
        myLocation.getLocation(this, locationResult);
    }

    @Override
    public void onDestroy() {
        Log.v(ApplicationName, "SensingService.onDestroy");
        super.onDestroy();
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.v(ApplicationName, "SensingService.onHandleIntent");
        if (mSensorManager != null) {
            registerListeners();
        }
    }

    public LocationResult locationResult = new LocationResult() {
        @Override
        public void gotLocation(final Location location) {
            if (location != null) {
                Log.v(ApplicationName, "Location != null : (" + location.getLatitude() + "," + location.getLongitude() + ")");
            } else {
                Log.v(ApplicationName, "Location == null : (0,0)");
            }
        }
    };

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent currentEvent) {
        if (currentEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
            return;
        }

        synchronized (this) {
            float[] accelVals = null;
            float totalForce = 0.0f;

            int sensor = currentEvent.sensor.getType();
            System.arraycopy(currentEvent.values, 0, mAccelerationValues, 0, 3); // We use System.arraycopy because of this:
            switch (sensor) {
            case Sensor.TYPE_ACCELEROMETER:
                sensorType = "Accelerometer";
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues); 
                break;
            case Sensor.TYPE_LINEAR_ACCELERATION:
                sensorType = "LinearAcceleration";
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues) + 1; 
                break;
            case Sensor.TYPE_GRAVITY:
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues); 
                sensorType = "Gravity";
                break;
            } 
            Log.v(ApplicationName,DateHelper.GetUTCdatetimeFromDate(new Date()) + " - from sensingService");
        }
    }

    private void registerListeners() {
        Log.v(ApplicationName, "Registering sensors listeners");
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
    }
}

actualización 2

Ahora he agregado esto en el método Encreate:

int NOTIFICATION_ID = 1;
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0);
Notification notification = new Notification(R.drawable.ic_dialog_info, "Running in the Foregound", System.currentTimeMillis());
notification.setLatestEventInfo(this, "Title", "Text", pi);
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, notification);

Para comenzar como startfations, pero pone el icono en la barra de notificación, luego se llama OnDestroy en el servicio y se desaparece el icono de notificación.

Estoy desesperado ahora! Por favor ayuda en este!

¡Gracias! Guillermo.

¿Fue útil?

Solución 2

OK, vi una respuesta a otra pregunta, y hay un tipo que dijo que es un error en Android, seguí su sugerencia para mover el código a Oncreate en lugar de OnHandleintent y funcionó!Entonces, si nadie me muestra, es un problema con mi código, para mí será un error.¡Gracias!

Otros consejos

según Documentación intentservice :

El servicio se inicia según sea necesario, maneja cada intención a su vez usando un Hilo de trabajador, y se detiene en sí mismo cuando se queda sin trabajo

Además, de acuerdo con la misma documentación, se supone que no debe anular onStartCommand() y onDestroy() en su IntentService, asumo porque implementa su propio comportamiento especial como se especifica anteriormente.Tal vez necesite extender Service en lugar de IntentService.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top