java.lang.IllegalStateException:尝试运行RingtoneService时不允许启动服务意图

Pie*_*aly 2 service android exception android-mediaplayer android-studio

我正在创建一个包含许多功能的管理器应用程序,其中一个是警报,而在大多数情况下尝试启动警报时,我都会收到此异常“ java.lang.IllegalStateException:不允许启动服务意图”,因为它是在后台运行(有时会延迟运行)!我广泛地寻找答案,并尝试了以下方法,但均无济于事:-JobScheduler:我遇到相同的异常-bindService()并在onServiceConnected()中编写代码:它从未命中过onServiceConnected()

以下是我的代码的重要部分:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {

        Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
        context.startService(serviceIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

来自以下活动的广播电话:

Intent intent = new Intent(AddAlarm.this, AlarmReceiver.class)
                .putExtra("ALARM_ON", true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Run Code Online (Sandbox Code Playgroud)

以下服务类别:

public class RingtonePlayingService extends Service {

    // Player
    MediaPlayer player;
    boolean isRunning;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (!isRunning) {

            player = MediaPlayer.create(this, R.raw.ringtone);
            player.start();

            this.isRunning = true;

            showNotification();

        }
        else if (isRunning) {

            player.stop();

            this.isRunning = false;

        }

        return START_STICKY;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sag*_*gar 6

如果您在Android 8.0上运行代码,则可能会出现这种情况。根据文档(从Android 8.0开始),如果您的应用程序不在前台,则无法在后台启动服务。您需要替换以下内容:

Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);
Run Code Online (Sandbox Code Playgroud)

Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );
Run Code Online (Sandbox Code Playgroud)

确保startForeground()使用通知调用onHandleIntent。您可以参考此SO以获得实现它的详细信息。

  • 这不是最佳解决方案。您不应该简单地启动一堆长期运行的前台服务。最好扩展JobIntentService而不是Service,并继续使用startService,这是一个更好的解决方案。 (2认同)