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.
 
     
     
    