在运行服务时唤醒锁定

时间:2012-09-28 19:43:43

标签: android service android-wake-lock

我想知道这是实现唤醒锁定的正确方法,以使我的设备在处于睡眠模式后重新开启。设备重新启动后,它将从该点启动一个意图。真的,我只想让屏幕亮起足够长的时间才能发生意图。如果没有指针会很棒,我是否正确地做到了这一点!

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;
private PowerManager.WakeLock wl;

/** 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) {
    // TODO Auto-generated method stub

}

@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 > 0.5) {
        AlertDialog alert = new AlertDialog.Builder(GMeter.this).create();
        alert.setTitle("-=Warning=-");
        alert.setMessage("Incoming Game!");
        alert.show();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP + PowerManager.FULL_WAKE_LOCK, "myTag");
        wl.acquire();
        wl.release();
        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) {
    // TODO Auto-generated method stub
    return null;
}

}

1 个答案:

答案 0 :(得分:0)

不,唤醒锁被用来防止设备睡觉。我想你应该使用AlarmManager功能来唤醒你的设备并发送一个意图(参数RTC_WAKEUP)。

修改:如果您希望在服务的onCreate()方法中使用自己的功能,则应获取PARTIAL_WAKE_LOCK,并应在onDestroy()中将其释放。因此,您的服务将收到通知。或者你可以每隔n秒唤醒你的设备并检查你的传感器。