0

How can I run service in background in oreo? This service class is working good in all Android versions below Oreo, and I declared this service in manifest. In my activity class I launch with startservice(getApplicationContext,ExoService.class).

public class ExoService extends Service {
private static Context context;
private static ItemRadio station;
private static ExoService service;
public static SimpleExoPlayer exoPlayer;
private static Uri uri;
private WifiManager.WifiLock wifiLock;
static ProgressTask task;

/*binder return null*/

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    task = new ProgressTask();
    task.execute();
    return START_STICKY;
/*Alrady set Start Sticky*/

 }

/*here is initilize service class*/

static public void initialize(Context context, ItemRadio station) {
    ExoService.context = context;
    ExoService.station = station;
    Log.e("inwhich", "");
}

/*this is my service instance*/

static public ExoService getInstance() {
    if (service == null) {
        service = new ExoService();
    }
    return service;
}

/*Oncreate method */

@Override
public void onCreate() {
    super.onCreate();
    try {
        TrackSelector trackSelector = new DefaultTrackSelector();
        LoadControl loadControl = new DefaultLoadControl();
        exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

/*public void stop() {
    if (exoPlayer != null && exoPlayer.getPlayWhenReady()) {
        exoPlayer.stop();
        exoPlayer.release();
        exoPlayer = null;
        this.wifiLock.release();
        this.stopForeground(true);
    }
}*/

public void start() {
    if (exoPlayer != null) {
        exoPlayer.setPlayWhenReady(true);
    }
}

/*after some second ondstroy method call in oreo.*/

public void onDestroy() {
    if (exoPlayer != null) {
        exoPlayer.stop();
    }
    Log.e("Destroyed", "Called");

}

/*public void pause() {
    if (exoPlayer != null) {
        exoPlayer.stop();
        // exoPlayer.setPlayWhenReady(false);
    }
}*/

public ItemRadio getPlayingRadioStation() {
    return station;
}

Async task for decoding songs url:

@SuppressLint("StaticFieldLeak")
private class ProgressTask extends AsyncTask<String, Void, Boolean> {

    protected void onPreExecute() {
    }

    protected Boolean doInBackground(final String... args) {

        /*boolean bool = true;*/

        try {
            uri = Uri.parse(station.getRadiourl());

            DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
            DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, getString(R.string.app_name)), bandwidthMeterA);

            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
            MediaSource audioSource = new ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null);
            /* exoPlayer.addListener(eventListener);
            MediaSource videoSource = new HlsMediaSource(uri, dataSourceFactory, 1, null, null);*/

            final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);

            if (station.getRadiourl().endsWith(".m3u8")) {
                exoPlayer.prepare(loopingSource);
            } else {
                exoPlayer.prepare(audioSource);
            }
            /*exoPlayer.setPlayWhenReady(true);*/

        } catch (IllegalArgumentException | IllegalStateException | SecurityException | NullPointerException e1) {
            e1.printStackTrace();
        }
        return true;
    }

    @SuppressLint("WifiManagerPotentialLeak")
    @Override
    protected void onPostExecute(final Boolean success) {

        try {
            if (success) {
                wifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE))
                        .createWifiLock(WifiManager.WIFI_MODE_FULL, "RadiophonyLock");
                wifiLock.acquire();

                exoPlayer.setPlayWhenReady(true);

            } else {
                /*Toast.makeText(context, context.getString(R.string.internet_disabled), Toast.LENGTH_SHORT).show();*/
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        /* dialog.dismiss();*/

    }
}
}`

After some time, the ondestroy method gets called automatically in oreo. How can I handle this?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Naveen
  • 21
  • 4
  • 1
    You need to use a `Foreground Service` for it. – ADM Mar 12 '18 at 07:27
  • Background services have been restricted in Oreo. You can check discussion in [this](https://stackoverflow.com/questions/48178194/android-oreo-keep-started-background-service-alive-without-setting-it-foregroun) post. Also check out [this](https://code.tutsplus.com/tutorials/background-audio-in-android-with-mediasessioncompat--cms-27030) tutorial – NightFury Mar 12 '18 at 07:38
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Mar 12 '18 at 10:49
  • Additionally, please do not make "code this for me plz" requests. _Stack Overflow_ is not a place to advertise free work requests. People are happy to help beginners here, but asking for free labour is too much. – halfer Mar 12 '18 at 10:50
  • Do you have a crash or stack trace for your failing code on Oreo? – halfer Mar 12 '18 at 10:51
  • ok @halfer after some second ondestroy method called automatically in oreo.i alrady upload my code. – Naveen Mar 12 '18 at 11:10
  • 1
    im beginner in android. im try to fix this error from last one month but i cant get any solution. i have alrady read so many tutorial. plz help me anyone... – Naveen Mar 12 '18 at 11:17
  • did that fixed? – sudha Apr 16 '18 at 09:51

1 Answers1

0

Since Oreo limits the use of background service you need to start a foreground service. Here's the documentation about restrictions of services in Oreo. A quote of it:

Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground. After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR.

Putting a service in foreground basically involves attaching the service to a notification which is visible to the user:

service.startForeground(NOTIFICATION_ID, notification);

The startForeground service is available since API 5 whereas startForegroundService comes with Oreo, so you need to check the API level of the device and start the service accordingly.

marcbaechinger
  • 2,759
  • 18
  • 21
  • i change target version 25. now its working fine in background in Oreo. – Naveen Mar 14 '18 at 11:53
  • 1
    That's not a solution as Play store will enforce target API 26 for updates pretty soon. Please read this blog post: https://android-developers.googleblog.com/2017/12/improving-app-security-and-performance.html – marcbaechinger Mar 14 '18 at 11:57