0

I am trying to make a program run in the background in android.I tried many service examples but it just got more complicate for me.
I am trying to run a simple app which Silents the phone when we turn it over(I know there is a Built feature exist but that for silencing the phone when it is on it back we just put the phone on its "face" and it is in silent mode ).
I am trying to do something similar like when we put the phone in our pocket the magnetic field shows the "y" is in "-num" (in num i mean number).
But when we turn the phone upside down it becomes "+num".
Here is the code that makes the phone silent and make sound:

package com.magnet2.com;

private SensorManager mSensorManager;
private Sensor mSensor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}

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

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}

  @Override
  protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
  }

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.values[1] >= 29 )
    {

        ((AudioManager) getSystemService(AUDIO_SERVICE))
          .setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

    }
    if (event.values[1] <= -29 )
        if (event.values[2] >= -15 && event.values[2] <= 2 )
    {
        ((AudioManager) getSystemService(AUDIO_SERVICE))
        .setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    }

  }

}  

But I don't know how to run it in the background.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141

1 Answers1

0

For operations like this where something needs to be done continuously in the background without interaction from the user, Service class is the best approach to do so.

And if you are new to services, this question would solve most of your doubts and online tutorials are just a Google search away!

Good luck!

Community
  • 1
  • 1
Swayam
  • 16,294
  • 14
  • 64
  • 102