问题
I am creating an organizer app which contains many functions one of them is an alarm, while trying to start the RingtoneService for my alarm most of the times I get this exception "java.lang.IllegalStateException: Not allowed to start service Intent" because it's running in the background (sometimes it runs with delay)! I extensively searched for an answer and tried the following and none worked: - JobScheduler : I get the same exception - bindService() and writing the code inside onServiceConnected() : it never hits the onServiceConnected()
Below are the important parts of my code:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);
}
}
Broadcast call from activity below:
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);
Service class below:
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;
}
}
回答1:
If you are running your code on Android 8.0 then this behavior is expected. Based on the documentation, starting from Android 8.0, you cannot start a service in background if your application is not in foreground. You need to replace following:
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);
Do
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );
Ensure to call startForeground()
in your onHandleIntent with notification. You can refer to this SO for details to implement it.
来源:https://stackoverflow.com/questions/49961273/java-lang-illegalstateexception-not-allowed-to-start-service-intent-while-tryin