<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SEND_SMS" />
As it is written,
READ_PHONE_STATE
is about the phoneSEND_SMS
is about SMS
Privileges. Give this one.Java
TelephonyManager and PhoneStateListener do something about it.
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String number) {
//The state is the number that indicates the state, and the number is the number that was received when the call was received.
switch(state) {
//Incoming event
case TelephonyManager.CALL_STATE_RINGING:
System.out.println(number + "It's an incoming call from Mr.");
break;
//Event at the start of a call
case TelephonyManager.CALL_STATE_OFFHOOK:
System.out.println("I started calling");
break;
//When changing to the standby state(When you hang up)Event
case TelephonyManager.CALL_STATE_IDLE:
System.out.println("I hung up the phone");
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
SmsManager does a good job.
Send text-based SMS. All I have to do is send an SMS, so I'll look into the details at another time.
String number = "09000000000"; //Destination phone number
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(
number,
null,
"Hello",
null,
null
);
Send a simple message to the person who called you, just saying "Hey !!".
MainActivity.java
package example.com.sample003;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// -----The important thing is ↓ from here ↓----- //
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String number) {
//The state is the number that indicates the state, and the number is the number that was received when the call was received.
switch (state) {
//Incoming event
case TelephonyManager.CALL_STATE_RINGING:
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(
number,
null,
"Hey!!",
null,
null
);
break;
//Event at the start of a call
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
//When changing to the standby state(When you hang up)Event
case TelephonyManager.CALL_STATE_IDLE:
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
// -----↑ Up to here ↑----- //
}
}