无法解析摇事件监听器getApplicationContext和startActivity方法:机器

2019-10-20 10:46发布

我想实现一摇事件侦听器和下面是我的代码。 这是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);
        }
    }
}

Answer 1:

这些方法不存在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);
        }
    }
}


文章来源: Unable to resolve getApplicationContext and startActivity methods in shake event listener: Android Studio