在电话睡着时唤醒锁定我的服务工作

时间:2012-09-28 14:59:01

标签: android android-wake-lock

现在我正在使用一种在后台计算G-Forces的服务,在达到一定数量的G后,它将启动一个意图。我想知道如何使用即使手机处于睡眠状态也能启动意图的唤醒锁定。

以下是我正在处理的代码:

public class GMeter extends Service implements SensorEventListener {

    private float mLastX, mLastY, mLastZ;
    private boolean mInitialized;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private final float NOISE = (float) 2.0;

    /** Called when the activity is first created. */
    public void onCreate() {
        mInitialized = false;
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
        Toast.makeText(this, "Starting Service", Toast.LENGTH_LONG).show();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {

    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        double a = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        double currentG = (a/ SensorManager.STANDARD_GRAVITY);
        if (!mInitialized && currentG > 1.0) {
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
            //Start Second Activity
            Intent intent = new Intent(GMeter.this,nextClass.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            float deltaX = Math.abs(mLastX - x);
            float deltaY = Math.abs(mLastY - y);
            float deltaZ = Math.abs(mLastZ - z);
            if (deltaX < NOISE) deltaX = (float)0.0;
            if (deltaY < NOISE) deltaY = (float)0.0;
            if (deltaZ < NOISE) deltaZ = (float)0.0;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
        }
    }

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

0 个答案:

没有答案