1 ) Main Activity
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener { public TextToSpeech tts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerReceiver(broadcastReceiver, new IntentFilter("broadCastName")); tts=new TextToSpeech(this,this); } @Override public void onInit(int status) { } PhoneStateReceiver broadcastReceiver = new PhoneStateReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); String message = b.getString("message"); tts.speak(message+"Calling",TextToSpeech.QUEUE_FLUSH,null); } }; }
2 ) Broadcast Receiver
public class PhoneStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); try { if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){ Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show(); TextToSpeech tts = null; tts.speak(incomingNumber+"Calling",TextToSpeech.QUEUE_FLUSH,null); } if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){ Toast.makeText(context,"Received State",Toast.LENGTH_SHORT).show(); } if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){ Toast.makeText(context,"Idle State",Toast.LENGTH_SHORT).show(); } } catch (Exception e){ e.printStackTrace(); } Bundle extras = intent.getExtras(); Intent i = new Intent("broadCastName"); // Data you need to pass to activity i.putExtra("message", extras.getString(incomingNumber)); context.sendBroadcast(i); } }Notes :1 ) Require Graddlecompile 'com.android.support:appcompat-v7:25.1.1'compile 'com.android.support:design:25.1.1'compile 'com.android.support:support-v4:25.1.1'
Comments
Post a Comment