Search code examples
androidandroid-sensorsonresumeonpausesensormanager

The method onPause( ), onResume( ) is undefined for the type


I a have class for ShakeListener and i have implemented onPause() and onResume() methods in that. My code for that is

package com.example.shakedemo;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import java.lang.UnsupportedOperationException;


public class ShakeListener
{
      private SensorManager mSensorManager;
      private float mAccel; // acceleration apart from gravity
      private float mAccelCurrent; // current acceleration including gravity
      private float mAccelLast; // last acceleration including gravity

  private final SensorEventListener mSensorListener = new SensorEventListener() {

    public void onSensorChanged(SensorEvent se) {
      float x = se.values[0];
      float y = se.values[1];
      float z = se.values[2];
      mAccelLast = mAccelCurrent;
      mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
      float delta = mAccelCurrent - mAccelLast;
      mAccel = mAccel * 0.9f + delta; // perform low-cut filter
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }


  };



  protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  }

  protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(mSensorListener);

  }
}

But it showing an error on both super.onPause(); and super.onResume(); lines which says

The method onPause() is undefined for the type Object

Is there any problem in implementing onResume and onPause in a class?

As i am a new one in android development please give me clear idea about that.


Solution

  • onResume and onPause are the methods of an Activity class. You are not overriding the activity.

    If the ShakeListener is an Activity you need to extends the Activity class. like

    public class ShakeListener extends Activity 
    

    And if that is not an Activity class, then do not call super versions.

    Just do them as

    public void registerListener() {
        mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
      }
    
      public void unregisterListener() {
        mSensorManager.unregisterListener(mSensorListener);
    
      }