问题描述
我正在创建一个管理器应用程序,其中包含许多功能,其中一个是闹钟,但在大多数情况下尝试为我的闹钟启动 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);
}
}
来自以下活动的广播电话:
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);
以下服务类:
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 );
确保通过通知在您的 onHandleIntent 中调用 startForeground()
.你可以参考这个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 时不允许启动服务 Intent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!