Остановка аудио в сервисе при поступлении звонка или изменении аудиофокуса
Есть сервис, который запускает аудио. Если в уведомлении нажать "Стоп" также останавливает аудио.
Как сделать чтобы при поступлении звонка или при изменении аудиофокуса сервис останавливал аудио (т.е. останавливал сам плеер.. для этого в классе AudioPlayer есть методы AudioPlayer.stopPlayer(); и AudioPlayer.startPlayer(stream, audioSource, this)), а при окончании звонка автоматически запускал.
Мне нужно решение или решения (в зависимости от версий API) начиная с Android API 24
.
public class AudioPlayerService extends Service {
public static Context context;
boolean isPlay = false;
String stream;
String audio;
String img;
String audioSource;
public static final String KEY_STREAM = AudioPlayerService.class.getSimpleName() + ".KEY_STREAM";
public static final String KEY_AUDIO = AudioPlayerService.class.getSimpleName() + ".KEY_RADIO";
public static final String KEY_IMG = AudioPlayerService.class.getSimpleName() + ".KEY_IMG";
public static final String KEY_AUDIO_SOURCE = AudioPlayerService.class.getSimpleName() + ".KEY_AUDIO_SOURCE"; //Источник аудио (интернет или локальные)
private TelephonyManager tm;
CallStateListener callStateListener;
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(AppConstants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Intent closeIntent = new Intent(this, AudioPlayerService.class);
closeIntent.setAction(AppConstants.ACTION.STOPFOREGROUND_ACTION);
PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, PendingIntent.FLAG_IMMUTABLE);
int notifyId = AppConstants.NOTIFICATION_ID.PLAYER_SERVICE_ID; // id уведомления
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "cradioID";
CharSequence channelName = "Radio Channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationManager notificationManager = getSystemService(NotificationManager.class);
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.playing) + " " + audio)
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.setColor(Color.RED)
.addAction(R.drawable.icon_stop, getResources().getString(R.string.stop), pCloseIntent)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
// Запуск службы в зависимости от версии Android
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(notifyId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
} else {
startForeground(notifyId, notification);
}
} else {
String legacyChannelId = "legacy_channel_id"; // псевдоканал для старых версий Android
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, legacyChannelId)
.setContentTitle(getResources().getString(R.string.playing) + " " + audio)
.setContentText(getResources().getString(R.string.open_list))
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(R.drawable.icon_stop, getResources().getString(R.string.stop), pCloseIntent)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
startForeground(notifyId, notification);
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
callStateListener = new CallStateListener();
tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private class CallStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
//Когда телефон звонит, то делаем паузу
if (isPlay) {
AudioPlayer.stopPlayer();
isPlay = false;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Когда телефон не звонит, то продолжаем проигрывание
if (!isPlay) {
isPlay = true;
AudioPlayer.startPlayer(stream, audioSource, AudioPlayerService.this);
}
break;
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
this.stream = intent.getStringExtra(KEY_STREAM);
this.audio = intent.getStringExtra(KEY_AUDIO);
this.audioSource = intent.getStringExtra(KEY_AUDIO_SOURCE);
this.img = intent.getStringExtra(KEY_IMG);
if (intent.getAction() != null && intent.getAction().equals(AppConstants.ACTION.STARTFOREGROUND_ACTION)) {
isPlay = true;
showNotification();
AudioPlayer.startPlayer(stream, audioSource, this);
} else if (intent.getAction() != null && intent.getAction().equals(AppConstants.ACTION.STOPFOREGROUND_ACTION)) {
isPlay = false;
stopAudioService();
}
return START_REDELIVER_INTENT;
}
private void stopAudioService() {
Intent brIntent = new Intent(AppConstants.BROADCAST_ACTION);
brIntent.putExtra(AppConstants.SERVICE_PARAM, AppConstants.SERVICE_STATUS);
sendBroadcast(brIntent);
AudioPlayer.stopPlayer();
stopForeground(true);
RadioPlayerActivity.isPlay = false;
stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
}
AudioPlayer.stopPlayer();
stopForeground(true);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}