有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当应用程序在Oreo中处于后台时,java音乐服务在几秒钟后不工作

如何在oreo中运行后台服务?这个服务类在Oreo以下的所有Android版本中都运行良好,我在清单中声明了这个服务。在我的活动课上,我用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;
}

解码歌曲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();*/

    }
}
}`

一段时间后,ondestroy方法会在oreo中自动调用。我该怎么办


共 (1) 个答案

  1. # 1 楼答案

    因为Oreo限制了后台服务的使用,所以你需要启动前台服务。这里是关于奥利奥的服务限制。其中一句话:

    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.

    将服务置于前台基本上涉及将服务附加到用户可见的通知:

    service.startForeground(NOTIFICATION_ID, notification);
    

    startForeground服务从API 5开始提供,而startForeground服务随Oreo提供,因此您需要检查设备的API级别,并相应地启动服务