Domanda

Nella mia applicazione OnCreate I Controllare alcune condizioni e poi avvio un'attività come questa:

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

Da quell'attività iniziano un intentuservice che registra alcuni ascoltatori per i sensori, è iniziato come appiccicoso che significa che dovrebbe essere interrotto esplicitamente. Che Intentvice monitora i sensori.

Il mio problema è che quando torno alla prima attività, i sensori non sono più rilevanti (ho messo un log.v in onsensorchanged (inizio mostrando i dati, e poi si arresta).

Perché potrebbe essere che si ferma se non l'avessi fermato esplicitamente? Inoltre vedo che a volte trovo sudestroy di Intentservice viene chiamato, ma di nuovo, come può essere chiamato se è appiccicoso e non ho chiamato fermo () e non si è fermato in nessun altro modo?

Grazie! Guillermo.

Modifica

Questo è il codice dell'intentvice (che dovrebbe essere in esecuzione tutto il tempo, nonostante se il cellulare va a dormire o il pulsante Home è premuto (conosco la batteria e tutto il resto, l'utente sarà avvisato di questo e avere l'oportunità per chiudere l'applicazione quando vuole.

Il servizio è chiamato da Maineactivity come questo:

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

E il codice di servizio è questo:

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);
    }
}
.

Aggiorna 2

Ora ho aggiunto questo sul metodo OnCreate:

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);
.

Per avviarlo come startForroground, ma mette l'icona nella barra di notifica, allora OnDestroy è chiamato nel servizio e l'icona della notifica va via.

Sono disperato ora! Per favore aiuto in questo!

Grazie! Guillermo.

È stato utile?

Soluzione 2

Ok, ho visto una risposta ad un'altra domanda, e c'è un ragazzo che ha detto che è un bug in Android, ho seguito il suo suggerimento per spostare il codice per oncreare invece di suhandleintent e ha funzionato!Quindi, se nessuno mi mostri è un problema con il mio codice, per me sarà un bug.Grazie!

Altri suggerimenti

come a Documentazione Intentservice :

.

Il servizio è iniziato se necessario, gestisce ogni intento a sua volta usando a Discussione del lavoratore, e si ferma quando esaurisce il lavoro

Inoltre, in base alla stessa documentazione, non dovresti sovrascrivere onStartCommand() e onDestroy() nel tuo IntentService, presumo perché implementa il proprio comportamento speciale come specificato sopra.Forse è necessario estendere Service anziché IntentService.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top