我正在创建一个包含许多功能的管理器应用程序其中一个是警报,而在尝试为我的警报启动RingtoneService时,大多数情况下我都会收到此异常“java.lang.IllegalStateException:不允许启动服务Intent “因为它在后台运行(有时会延迟运行)! 我广泛搜索了一个答案并尝试了以下内容并且没有一个工作: - 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);
}
}
来自以下活动的广播电话:
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);
以下服务类:
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;
}
}
答案 0 :(得分:5)
如果您在Android 8.0上运行代码,则会出现此行为。基于documentation,从Android 8.0开始,如果您的应用程序不在前台,则无法在后台启动服务。您需要替换以下内容:
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);
<强>不要强>
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );
确保通过onHandleIntent通知startForeground()
。您可以参考此SO了解实施细节。