Search code examples
androidbackgroundandroid-studioaccelerometer

override on background service in an android app


I want press button in MyActivity.java. When the button is pressed, the accelerometer should start in the background.

I use this code in MyActivity.java:

    // buttonBackground
    buttonStatistics.setOnClickListener(new View.OnClickListener(){
        // wordt uitgevoerd wanneer je klikt
        @Override
        public void onClick(View v){
            Log.d(TAG, "onClick: starting service");
            startService(new Intent(MyActivity.this, background.class));
            Toast.makeText(getApplicationContext(),
                    "Running in Background activated!", Toast.LENGTH_LONG).show();
      //      startActivity(new Intent(MyActivity.this, statistics.class));
        }
    });

In background.java, I want to run the onCreate() function automatically when the button above is pressed.

Code background.java:

public class background extends Service implements SensorEventListener {

    public SensorManager sensorManager;
    public Sensor sensorAccelerometer;
    private static final String TAG = "background";

    CountDownTimer countDownTimer;

//    @override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate();
        Log.d(TAG, "onCreate");
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        //   sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);

        alert();
    }

I tried to put @override above onCreate(), but this is a service and not an Activity(and it does not work).

Question: I want run onCreate() in background.java automatically when I press the button in MyActivity.java.

The application works I get no errors, but it does not work the way I want.

Any help is appreciated.


Solution

  • In Service, you have onStartCommand method:

    So put the code you want to execute in onStartCommand()

    public class Background extends Service implements SensorEventListener {
    
        public SensorManager sensorManager;
        public Sensor sensorAccelerometer;
        private static final String TAG = "background";
    
        CountDownTimer countDownTimer;
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //your code
            return START_STICKY;
        }
    }