Your experience on this site will be improved by allowing cookies
We can know the incoming number in Android, while the phone is in the ringing mode. The Android Speech API and telephony manager are used to speak the incoming number.
In the below example, we are using the Android Speech API and telephony manager to develop an app that speaks the incoming number while the phone is in the ringing mode.
activity_main.xml:
In the activity_main.xml file, we will add a TextView from the palette.
Activity class:(File: MainActivity.java)
In the MainActivity.java file, we will write the code to know the phone state. The code will then speak the incoming number with the help of the TextToSpeech class.
package com.example.radioapp; import java.util.Locale; import android.media.AudioManager; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.Toast; import android.speech.tts.TextToSpeech; public class MainActivity extends Activity implements TextToSpeech.OnInitListener { private TextToSpeech tts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tts = new TextToSpeech(this, this); TelephonyManager telephonyManager = (TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE); PhoneStateListener callStateListener = new PhoneStateListener() { public void onCallStateChanged(int state, String incomingNumber){ if(state==TelephonyManager.CALL_STATE_RINGING){ tts.speak(incomingNumber+" calling", TextToSpeech.QUEUE_FLUSH, null); Toast.makeText(getApplicationContext(),"Ringing : "+incomingNumber, Toast.LENGTH_LONG).show(); } if(state==TelephonyManager.CALL_STATE_OFFHOOK){ Toast.makeText(getApplicationContext(),"In a call", Toast.LENGTH_LONG).show(); } if(state==TelephonyManager.CALL_STATE_IDLE){ //phone is neither ringing nor in a call } } }; telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = tts.setLanguage(Locale.US); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language not supported"); } else { } } else { Log.e("TTS", "Initialization Failed!"); } } @Override public void onDestroy() { // Don't forget to shutdown tts! if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } } |
AndroidManifest.xml:
In the AndroidManifest.xml file, we will add the READ_PHONE_STATE uses permission.
0 comments