在我的应用程序 onCreate 中,我检查一些条件,然后启动一个 Activity,如下所示:

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

从该 Activity 中,我启动一个 IntentService,它为传感器注册一些侦听器,它以 STICKY 方式启动,这意味着它应该显式停止。该 IntentService 监视传感器。

我的问题是,当我回到第一个 Activity 时,传感器不再感应(我将 Log.v 放入 onSensorChanged (开始显示数据,然后停止)。

如果我没有明确停止它,为什么它会停止?此外,我有时会看到 IntentService 的 OnDestroy 被调用,但同样,如果它是 STICKY 并且我没有调用 stopself() 并且没有以任何其他方式停止,它怎么能被调用呢?

谢谢!吉列尔莫.

编辑

这是 IntentService 的代码(它应该一直运行,尽管手机进入睡眠状态或按下主页按钮(我了解电池和其他所有内容,用户将收到关于此的警告,并且将有机会在他想要的时候关闭应用程序。

该服务从 MainActivity 中调用,如下所示:

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

服务代码是这样的:

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

更新2

现在我已将其添加到 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);

将其作为 startForground 启动,但它将图标放在通知栏中,然后在服务中调用 onDestroy 并且通知图标消失。

我现在很绝望!请帮忙解决这一问题!

谢谢!吉列尔莫.

有帮助吗?

解决方案 2

好的,我看到了对另一个问题的回复,还有一个人说这是Android中的一个错误,我跟着他的建议将代码移动到OnCreate而不是OnHandleIntent,而且它运作了!所以,如果没有人向我展示这是我的代码的问题,对于我来说,这将是一个错误。谢谢!

其他提示

按照 意图服务文档:

该服务是根据需要启动的,依次使用工人线程处理每个意图, 当工作用完时它会自动停止

另外,根据相同的文档,您不应该覆盖 onStartCommand()onDestroy() 在你的 IntentService, ,我认为是因为它实现了上面指定的自己的特殊行为。也许你需要延长 Service 代替 IntentService.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top