无法解决震动事件监听器中的getApplicationContext和startActivity方法:Android Studio

时间:2014-07-09 17:22:33

标签: android accelerometer shake launching-application

我正在尝试实现一个摇动事件监听器,下面是我的代码。如果重要的话,它是Android Studio环境。它只是说无法解析方法getApplicationContext甚至startActivity。任何人都可以帮我找到我的错误吗?

package com.shaivaldesai.shake;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

/**
 * Created by Shaival Desai on 7/3/14.
 */
public class ShakeEventListener implements SensorEventListener {


    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    // Low pass filter
    private float calcMaxAcceleration(SensorEvent sensorEvent) {

        final float alpha = 0.8f;

        float[] gravity = {-9.81f};

        gravity[0] = alpha * gravity[0] + (1 - alpha) * sensorEvent.values[0];
        gravity[1] = alpha * gravity[1] + (1 - alpha) * sensorEvent.values[1];
        gravity[2] = alpha * gravity[2] + (1 - alpha) * sensorEvent.values[2];

        float accX = sensorEvent.values[0] - gravity[0];
        float accY = sensorEvent.values[1] - gravity[1];
        float accZ = sensorEvent.values[2] - gravity[2];

        float max1 = Math.max(accX, accY);
        return Math.max(max1, accZ);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //handleShake(sensorEvent);}
    float maxAcc = calcMaxAcceleration(sensorEvent);
       // void handleShake(sensorEvent){
        //float maxAcc = calcMaxAcceleration(sensorEvent);
        if(maxAcc>=15) {

        Intent intent = new Intent(getApplicationContext(),Main.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

SensorEventListener中不存在这些方法。您必须从扩展Activity的类中复制此内容。您需要在Context对象上调用这些方法。您应该在ShakeEventListener上定义一个带有Context对象的自定义构造函数:

public class ShakeEventListener implements SensorEventListener {
    private Context mContext;

    public ShakeEventListener(Context context) {
        mContext = context;
    }

    /** omitting unchanged methods **/

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //handleShake(sensorEvent);}
        float maxAcc = calcMaxAcceleration(sensorEvent);
        // void handleShake(sensorEvent){
        //float maxAcc = calcMaxAcceleration(sensorEvent);
        if(maxAcc>=15) {

            Intent intent = new Intent(mContext, Main.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
    }
}