0

When I close my application, my thread is still working, but it randomly stops SensorListener and MusicPlayer after a few minutes. When I open my app, it works again.

How do I start my thread from MainActivity:

new backgroundThread(MainActivity.this).start();

My thread code:

public class backgroundThread extends Thread implements SensorEventListener{
    private Context context;
    public backgroundThread(Context context){this.context = context;}
    public SensorManager sensorManager;

    MediaPlayer mediaPlayer;
    MediaPlayer mediaPlayer2;

In a "run" function:


mediaPlayer = MediaPlayer.create(context, R.raw.alert);
            mediaPlayer2 = MediaPlayer.create(context, R.raw.cancel);
            sensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);

sensorManager.registerListener(this, sensorManager.getDefaultSensor
                                    (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);

mediaPlayer.start();

In my terminal acceleration isn't changing when I shake my device, but it's refreshing, so OnSensorChanged() function runs.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • 2
    Please read about [background processing in Android](https://developer.android.com/guide/background) . Your threads will be stop when the app is stopped. – Zohaib Amir Aug 14 '19 at 11:00
  • In your question the Android Studio has no significance. "Android Studio's thread" reads as if your IDE doesn't work properly, while you have issues with the application thread running on the Android device, not with the IDE. And it doesn't work well, because Android OS is designed like that, i.e. what Amir says above, it's lot more complicated to run background task on Android OS, as generally these are not welcome (eats through battery, or may pose extra security risk), so you must use the designed API calls and fulfill the requirements to have background task running and not killed. – Ped7g Aug 14 '19 at 11:11
  • 2
    Beside everything said, I think you should use foreground service (I think Google Music is using that): https://developer.android.com/guide/components/services – Janusz Hain Aug 14 '19 at 11:45
  • It looks like when I implement these elements into a service, it works in the same way. – Mateusz Szwedka Aug 15 '19 at 19:10

0 Answers0