There is an active where the audio is played. Tell me how to make it so that when someone calls, the playback volume decreases, and when the call ends again, normal?

Here is the activity code

public class Player extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener { private TextView txtSongText; private ImageView img; private ImageButton btnPlay; private ImageButton btnFavorites; private ImageButton btnPrev; private ImageButton btnNext; MediaPlayer mediaPlayer; AudioManager am; NotificationManager notificationManager; Notification builder; BroadcastReceiver br; KidsDBHeler dbHeler; private boolean isPlay; private String title = ""; private String text = ""; private String filename = ""; private String image = ""; private String author = ""; private String source = ""; private int favorite; private int currentId = 0; private String MAYBE_ACTION = "MAYBE_ACTION"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player); title = getIntent().getExtras().getString("title"); dbHeler = new KidsDBHeler(this); am = (AudioManager) getSystemService(AUDIO_SERVICE); img = (ImageView) findViewById(R.id.img); btnPlay = (ImageButton) findViewById(R.id.btnPlay); btnFavorites = (ImageButton) findViewById(R.id.btnFavorites); btnPrev = (ImageButton) findViewById(R.id.btnPrev); btnNext = (ImageButton) findViewById(R.id.btnNext); txtSongText = (TextView) findViewById(R.id.txtSongText); String query = "SELECT * " + " FROM " + KidsContract.KidsEntry.TABLE_SONGS + " WHERE " + KidsContract.KidsEntry.COLUMN_TITLE + " = " + "\"" + title + "\""; navPrevNext(query); } public void onPlay(View view) { if (mediaPlayer == null) { return; } if (isPlay == true) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); btnPlay.setImageResource(R.drawable.icon_play); isPlay = false; } } else if (isPlay == false) { if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); btnPlay.setImageResource(R.drawable.icon_pause); isPlay = true; } } } public void onPrev(View view) { currentId--; if (currentId < 1) { btnPrev.setEnabled(false); currentId++; } else { btnPrev.setEnabled(true); btnNext.setEnabled(true); String query = "SELECT * " + " FROM " + KidsContract.KidsEntry.TABLE_SONGS + " WHERE " + KidsContract.KidsEntry._ID + " = " + currentId; navPrevNext(query); NotificationManager notifManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifManager.cancelAll(); unregisterReceiver(br); createNotifycation(); } } public void onNext(View view) { currentId++; if (currentId > dbHeler.getDBItemCount()) { btnNext.setEnabled(false); currentId--; } else { btnPrev.setEnabled(true); btnNext.setEnabled(true); String query = "SELECT * " + " FROM " + KidsContract.KidsEntry.TABLE_SONGS + " WHERE " + KidsContract.KidsEntry._ID + " = " + currentId; navPrevNext(query); NotificationManager notifManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifManager.cancelAll(); unregisterReceiver(br); createNotifycation(); } } @Override protected void onResume() { super.onResume(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { currentId++; if (currentId > dbHeler.getDBItemCount()) { btnNext.setEnabled(false); currentId--; System.out.println(currentId); } else { btnPrev.setEnabled(true); btnNext.setEnabled(true); String query = "SELECT * " + " FROM " + KidsContract.KidsEntry.TABLE_SONGS + " WHERE " + KidsContract.KidsEntry._ID + " = " + currentId; navPrevNext(query); createNotifycation(); } } }); createNotifycation(); } @Override public void onPrepared(MediaPlayer mp) { mp.start(); } @Override public void onCompletion(MediaPlayer mp) { } @Override protected void onDestroy() { NotificationManager notifManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifManager.cancelAll(); super.onDestroy(); releaseMP(); unregisterReceiver(br); } private void releaseMP() { if (mediaPlayer != null) { try { mediaPlayer.release(); mediaPlayer = null; } catch (Exception e) { e.printStackTrace(); } } } //Метод для выгрузки из БД и воспроизведения аудио public void navPrevNext(String query) { Cursor cursor = dbHeler.database.rawQuery(query, null); try { if (cursor.getCount() != 0) { while (cursor.moveToNext()) { title = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_TITLE)); text = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_TEXT)); filename = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_FILENAME)); image = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_IMAGE)); favorite = cursor.getInt(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_FAVORITE)); currentId = cursor.getInt(cursor.getColumnIndex(KidsContract.KidsEntry._ID)); author = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_AUTHOR)); source = cursor.getString(cursor.getColumnIndex(KidsContract.KidsEntry.COLUMN_SOURCE)); if (favorite == 1) { btnFavorites.setImageResource(R.drawable.icon_star_yellow); } else if (favorite == 0){ btnFavorites.setImageResource(R.drawable.icon_star_outline_black); } actionBar = getSupportActionBar(); SpannableString s = new SpannableString(title); s.setSpan(new TypefaceSpan(this, "Dolores.otf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); actionBar.setTitle(s); if (source == null || source.isEmpty()) { txtSongText.setText(title); } else { txtSongText.setText(title + " - " + source); } txtSongText.append("\n"); txtSongText.append(author); txtSongText.append("\n\n"); txtSongText.append(text.replace("\\n", "\n")); try { InputStream ims = getAssets().open("img/" + image + ".jpg"); Drawable d = Drawable.createFromStream(ims, null); img.setImageDrawable(d); } catch(IOException ex) { return; } } } } catch (SQLException ex) { } finally { cursor.close(); } releaseMP(); try { AssetFileDescriptor afd = getAssets().openFd("music/" + filename + ".mp3"); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); mediaPlayer.prepare(); mediaPlayer.start(); isPlay = true; btnPlay.setImageResource(R.drawable.icon_pause); } catch (IOException ex) { ex.printStackTrace(); } if (mediaPlayer == null) { return; } } public void createNotifycation() { notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent intent = new Intent(this, Player.class); intent.putExtra("title", title); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); Intent closeIntent = new Intent(); closeIntent.setAction(MAYBE_ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 12345, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT >= 16) { builder = new Notification.Builder(this) .setTicker(title) .setContentTitle("Играет: " + title) .setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pIntent) .addAction(R.drawable.icon_stop, "Стоп", pendingIntent) .build(); builder.flags = builder.flags | Notification.FLAG_INSISTENT | Notification.FLAG_ONGOING_EVENT; notificationManager.notify(0, builder); } else { } br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION); registerReceiver(br, intentFilter); } } 

I read about getting and losing focus, but did not figure out how to work with it.

    1 answer 1

    If you need to reduce the sound during a call, then you need to process not the loss of focus, but messages from the TelephonyManager :

     PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { .... } }; TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); int events = PhoneStateListener.LISTEN_CALL_STATE; tm.listen(phoneStateListener, events); 

    For details here .