Please tell me how when an incoming call to reduce the sound in the application. There is a player that plays audio, it is necessary that when an incoming call, the sound is automatically reduced, and after the end of the call is restored. I read that you need to use telephonymanager, but did not quite understand how. Can I have a little example?
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private BroadcastReceiver receiver; private TelephonyManager tm; TextView callState; CallStateListener callStateListener; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); callStateListener = new CallStateListener(); tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE); callState = (TextView) findViewById(R.id.callState); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.PHONE_STATE")) { String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE); if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING) || phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) { ringing(); } else if (phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE)) { notRinging(); } } } }; IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.PHONE_STATE"); registerReceiver(receiver,filter); } @Override protected void onPause() { super.onPause(); tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE); } private class CallStateListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_RINGING: callState.setText("Is Ringing"); break; case TelephonyManager.CALL_STATE_IDLE: callState.setText("Not ringing"); break; } } } private void notRinging() { // Π΄Π΅ΠΉΡΡΠ²ΠΈΡ, ΠΊΠΎΠ³Π΄Π° ΡΠ΅Π»Π΅ΡΠΎΠ½ Π·Π°ΠΊΠΎΠ½ΡΠΈΠ» Π·Π²ΠΎΠ½ΠΎΠΊ Log.i(TAG, "notRinging: "); callState.setText("notRinging"); } private void ringing (){ // Π΄Π΅ΠΉΡΡΠ²ΠΈΡ, ΠΊΠΎΠ³Π΄Π° ΡΠ΅Π»Π΅ΡΠΎΠ½ Π·Π²ΠΎΠ½ΠΈΡ ΠΈΠ»ΠΈ ΠΏΠΎ Π½Π΅ΠΌΡ ΡΠ°Π·Π³ΠΎΠ²Π°ΡΠΈΠ²Π°ΡΡ Log.i(TAG, "ringing: "); callState.setText("ringing"); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } }
tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);remove fromonPause()and transfer toonDestroy()then this code will have to work until the activation is destroyed, that is, even if it is not in the foreground. - pavlofff