java.lang.IllegalStateException:尝试运行RingtoneService时不允许启动服务意图 [英] java.lang.IllegalStateException: Not allowed to start service Intent while trying to run RingtoneService
问题描述
我正在创建一个包含许多功能的管理器应用,其中一个是警报,而在大多数情况下,尝试启动警报的RingtoneService时都会收到此异常 java.lang.IllegalStateException:不允许启动服务意图,因为它在后台运行(有时会延迟运行)!
我广泛地寻找答案,然后尝试了以下方法,但均无济于事:
-JobScheduler:我遇到了相同的异常
-bindService()并将代码写入onServiceConnected()内:从未成功onServiceConnected()
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);
}
}
以下活动的广播通话:
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;
}
}
推荐答案
如果如果您在Android 8.0上运行代码,则可能会出现这种情况。根据文档,从Android 8.0开始,您无法启动如果您的应用程序不在前台,则在后台提供服务。您需要替换以下内容:
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);
做
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );
确保在您的计算机中调用 startForeground()
带有通知的onHandleIntent。您可以参考此 SO 以获得实施它的详细信息。
Ensure to call startForeground()
in your onHandleIntent with notification. You can refer to this SO for details to implement it.
这篇关于java.lang.IllegalStateException:尝试运行RingtoneService时不允许启动服务意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!