Hi I searched a lot on this forum for correct result but unable to find. I need details of last outgoing call once call is ended. For this I am using BroadcasteReceiver here is code for my receiver
public class CallStateBroadcaster extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}}
Here is code for PhoneStateListener
public class CustomPhoneStateListener extends PhoneStateListener{
private Context context;
public CustomPhoneStateListener(Context paramContext)
{
this.context = paramContext;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// TODO Auto-generated method stub
super.onCallStateChanged(state, incomingNumber);
((TelephonyManager)this.context.getSystemService("phone")).listen(this, PhoneStateListener.LISTEN_NONE);
if(TelephonyManager.CALL_STATE_IDLE == state)
{
try {
Thread.sleep(1500L);
Intent intent = new Intent(this.context,LastCallInfoActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is code for my activity which fetch call details for call log
public class LastCallInfoActivity extends Activity{
String addtolist;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Cursor callDetailCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null,null,null,android.provider.CallLog.Calls.DATE + " DESC limit 1");
int phoneNumber= callDetailCursor.getColumnIndex(CallLog.Calls.NUMBER);
int callType=callDetailCursor.getColumnIndex(CallLog.Calls.TYPE);
int callDate=callDetailCursor.getColumnIndex(CallLog.Calls.DATE);
int callDuration=callDetailCursor.getColumnIndex(CallLog.Calls.DURATION);
Log.i(">>CAllDetails", "getsCallLogs" );
if(callDetailCursor.getCount()>0)
{
while(callDetailCursor.moveToNext())
{
String phoneNumberString=callDetailCursor.getString(phoneNumber);
String contactName= getContactName(this, phoneNumberString);
String callTypeString =callDetailCursor.getString(callType);
String callDateString=callDetailCursor.getString(callDate);
String callDurationString=callDetailCursor.getString(callDuration);
Date callDayTime=new Date(Long.valueOf(callDateString));
int callCode = Integer.parseInt(callTypeString);
int calldur=Integer.parseInt(callDurationString);
if (callCode==2 && calldur>=1)
{
Double callCost=Double.parseDouble(callDurationString);
String callCostString= String.valueOf( callCost);
Log.i(">>CAllDetails", "getsLocation" );
addtolist= "Name :"+contactName+"\n"+
"Phone Number: "+phoneNumberString+"\n"+"Call Duration :"+
callDurationString+" Seconds\n"+"Call Date: "+callDayTime+"\n"+
callCostString;
}
}
}callDetailCursor.close();
Toast.makeText(this, addtolist, Toast.LENGTH_LONG).show();
}
public String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
}
My this program show toast even before my call got disconnected and start my activity. Please help me and correct my code so that it will get executed after call ends
thanks
just try this add an additional if statement for checking previous sate was off hook.
boolean wasoffhook=false;
if(TelephonyManager.CALL_STATE_OFFHOOK == state)
{
wasoffhook=true;
}
if(TelephonyManager.CALL_STATE_IDLE == state&&wasoffhook)
{
try {
Thread.sleep(1500L);
Intent intent = new Intent(this.context,LastCallInfoActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In your onreceive method of Callstatebroadcaster add this code and it would work fine.I just solved it.
#Override
public void onReceive(Context context, Intent intent)
{
try
{
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL"))
{
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
Toast.makeText(context,"the no. is"+savedNumber,Toast.LENGTH_LONG).show();
// onOutgoingCallStarted(context,"",callStartTime);
}
else
{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("Testing", "Outgoing call has been disconnect");
intent = new Intent(context, MyCustomDialog.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
System.out.println("CAll has been disconnect...............");
// Toast.makeText(this, "CAll has been disconnect", Toast.LENGTH_LONG).show();
break;
}
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
And in Callstatechanged method add this code.
public void onCallStateChanged(Context context, int state, String number)
{
if(lastState == state)
{
//No change, debounce extras
return;
}
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
// onIncomingCallStarted(context, number, callStartTime);
// onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
// onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
// wasRinging = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (!wasRinging) {
// Start your new activity
onIncomingCallEnded(context,savedNumber,callStartTime,new Date());
onOutgoingCallEnded(context,savedNumber,callStartTime,new Date());
} else {
onIncomingCallStarted(context,savedNumber,callStartTime);
// Cancel your old activity
}
// this should be the last piece of code before the break
break;
case TelephonyManager.CALL_STATE_IDLE:
if(isIncoming)
{
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
}
lastState = state;
}
This would work.
Related
I have a function to initiate an outbound phone call. I need to set up the listener to know the state of the call (ringing, hang-up, etc). I am having trouble figuring out how to do that and haven't found a tutorial that shows how. Here is the setup to place the call:
PhoneCall.kt
class PhoneCall : AppCompatActivity() {
private fun placeCall() {
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permision.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
telephonyManager.listen(CallListener, PhoneStateListener.LISTEN_CALL_STATE) //Not sure how to set up CallListener here?
val callIntent = Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber))
startActivity(callIntent)
}
}
}
I believe from CallListener I can create a when() to find the current state. But I'm not sure how to create CallListener and this doesn't appear to be a true listener? Does CallListener need to be a new class, object, or something else? I think I may need a Broadcast Receiver? I don't know the correct way to handle this.
I have a project where I do something similar I created two classes one PhoneCallListener and PhoneCallReceiver. I have removed some code that is used for my needs but if you implement these two classes you should be ok. I am no expert but I hope it helps you.
The jsonObject is just used as an example to show "doing something". I should also mention that I do not know Kotlin but I am told that Android Studio can convert the Java to Kotlin so it might help, hopefully someone more experienced will know how in Kotlin.
PhoneCallListener.java
public class PhoneCallListener extends PhoneCallReceiver {
#Override
protected void onIncomingCallStarted(Context c, String number, Date start) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Timestamp", App.getUTCTimestamp());
jsonObject.put("Direction", "incoming");
jsonObject.put("Number", number);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onOutgoingCallStarted(Context c, String number, Date start) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Timestamp", App.getUTCTimestamp());
jsonObject.put("Direction", "outgoing");
jsonObject.put("Number", number);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onIncomingCallEnded(Context c, String number, Date start, Date end)
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Timestamp", App.getUTCTimestamp());
jsonObject.put("Direction", "incoming call ended");
jsonObject.put("Number", number);
} catch (JSONException e) {
e.printStackTrace();
});
}
#Override
protected void onOutgoingCallEnded(Context c, String number, Date start, Date end) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Timestamp", App.getUTCTimestamp());
jsonObject.put("Direction", "outgoing call ended");
jsonObject.put("Number", number);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onMissedCall(Context c, String number, Date start) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Timestamp", App.getUTCTimestamp());
jsonObject.put("Direction", "missed");
jsonObject.put("Number", number);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
PhoneCallReceiver.java
abstract class PhoneCallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
private static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
try {
if (Objects.equals(intent.getAction(), "android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = Objects.requireNonNull(intent.getExtras()).getString("android.intent.extra.PHONE_NUMBER");
} else {
String stateStr = Objects.requireNonNull(intent.getExtras()).getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (number == null) {
number = "00000000000"; // Caller Withheld.
}
int state = 0;
assert stateStr != null;
if (!stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
state = TelephonyManager.CALL_STATE_OFFHOOK;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
state = TelephonyManager.CALL_STATE_RINGING;
}
}
onCallStateChanged(context, state, number);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start) {
}
protected void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
protected void onMissedCall(Context ctx, String number, Date start) {
}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if (lastState == state) {
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
} else if (isIncoming) {
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
I am trying add one thing in my app. What i am trying is whenever user get phone call or user make phone call, at same time recording should be start and recording must store in sd card after cutting the call.
Issues
1)Incoming call record work sometimes
2)Outgoing not working
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 0;
private DevicePolicyManager mDPM;
private ComponentName mAdminName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PackageManager p = getPackageManager();
p.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
try {
// Initiate DevicePolicyManager.
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mAdminName = new ComponentName(this, DeviceAdminDemo.class);
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
startActivityForResult(intent, REQUEST_CODE);
} else {
// mDPM.lockNow();
// Intent intent = new Intent(MainActivity.this,
// TrackDeviceService.class);
// startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode) {
Intent intent = new Intent(MainActivity.this, TService.class);
startService(intent);
}
}
}
TService
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
System.out.println("PATH"+path);
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
Remove this if (wasRinging == true) from TService, this wasRining Boolean checks if the phone was ringing some time before, i.e. when phone receives a call, in case of outgoing call it stays false so, the recorder part is skipped. Just change that and it should work.
Just replace your TService code with this..
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
public boolean didMakeACall = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging || didMakeACall) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
System.out.println("PATH"+path);
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
didMakeACall = true;
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
I'm afraid community wouldn't like external links here so I'm posting my quick demo project here...
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TService"/>
</application>
MainActivity.java
I'm starting TService in its onCreate method, please note that this could be any activity in your project, or any context you can start a service from.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, TService.class));
}
}
and now finally,
TService.java
I've tested this in Kitkat and Lollipop and it's working, for newer versions you need to explicitly ask for Manifest permissions during run time and it should work just as fine.
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
boolean didMakeACall = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging || didMakeACall) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/MyRecorder");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
System.out.println("PATH"+path);
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
didMakeACall = true;
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
I am trying to end the call the user dialed. Basically I would allow some number that user would be able to dial and call, else all other call would be end up and User would not be able to call other then those numbers.
Now the problem is I have tried several ways to do so , but its not working
What I am Doing:
I have a broadcast receiver Which got fired when User call the Number
Under It I gets the dialed number , if it is not my desired number I try to end it.
Here is what I am doing in my on Receive method.
public void onReceive(Context context, Intent intent) {
Log.d(OutgoingCallReceiver.class.getSimpleName(), intent.toString());
//TODO: Handle outgoing call event here
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
disconnectCall();
Toast.makeText(context, "DisConnecting! = "+phoneNumber, Toast.LENGTH_LONG).show();
killCall(context);
TelephonyManager tm=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Method m1 = null;
try {
m1 = tm.getClass().getDeclaredMethod("getITelephony");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
m1.setAccessible(true);
Object iTelephony = null;
try {
iTelephony = m1.invoke(tm);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Method m2 = null;
try {
m2 = iTelephony.getClass().getDeclaredMethod("silenceRinger");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Method m3 = null;
try {
m3 = iTelephony.getClass().getDeclaredMethod("endCall");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
// try {
// // m2.invoke(iTelephony);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
try {
m3.invoke(iTelephony);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
//telephonyService.silenceRinger();
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
// }
}
and Endig Call method as well
public void disconnectCall(){
try {
String serviceManagerName = "android.os.ServiceManager";
String serviceManagerNativeName = "android.os.ServiceManagerNative";
String telephonyName = "com.android.internal.telephony.ITelephony";
Class<?> telephonyClass;
Class<?> telephonyStubClass;
Class<?> serviceManagerClass;
Class<?> serviceManagerNativeClass;
Method telephonyEndCall;
Object telephonyObject;
Object serviceManagerObject;
telephonyClass = Class.forName(telephonyName);
telephonyStubClass = telephonyClass.getClasses()[0];
serviceManagerClass = Class.forName(serviceManagerName);
serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
Method getService = // getDefaults[29];
serviceManagerClass.getMethod("getService", String.class);
Method tempInterfaceMethod = serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
telephonyObject = serviceMethod.invoke(null, retbinder);
telephonyEndCall = telephonyClass.getMethod("endCall");
telephonyEndCall.invoke(telephonyObject);
} catch (Exception e) {
e.printStackTrace();
Log.d("Receiver",
"FATAL ERROR: could not connect to telephony subsystem");
Log.d("Receiver", "Exception object: " + e);
}
}
public boolean killCall(Context context) {
try {
// Get the boring old TelephonyManager
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Get the getITelephony() method
Class classTelephony = Class.forName(telephonyManager.getClass().getName());
Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
// Ignore that the method is supposed to be private
methodGetITelephony.setAccessible(true);
// Invoke getITelephony() to get the ITelephony interface
Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
// Get the endCall method from ITelephony
Class telephonyInterfaceClass =
Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
// Invoke endCall()
methodEndCall.invoke(telephonyInterface);
} catch (Exception ex) { // Many things can go wrong with reflection calls
Log.d("Receiver","PhoneStateReceiver **" + ex.toString());
return false;
}
return true;
}
As We can see I am using 4 different types of ways I found on internet to end the call , but its not working. At the moment I am trying this code on jelly beans. But its not working. Please help me if any one has I dea how to end the call and what is a proper way please help.
Code to kill call
public boolean killCall(Context context) {
try {
// Get the boring old TelephonyManager
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Get the getITelephony() method
Class classTelephony = Class.forName(telephonyManager.getClass().getName());
Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
// Ignore that the method is supposed to be private
methodGetITelephony.setAccessible(true);
// Invoke getITelephony() to get the ITelephony interface
Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
// Get the endCall method from ITelephony
Class telephonyInterfaceClass =
Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
// Invoke endCall()
methodEndCall.invoke(telephonyInterface);
} catch (Exception ex) { // Many things can go wrong with reflection calls
LogUtil.warn(TAG, "PhoneStateReceiver **" + ex.toString());
return false;
}
return true;
}
Code for different states
public abstract class PhoneCallReceiver extends BroadcastReceiver {
private static final String TAG = "PhoneCallReceiver";
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
private static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
} else {
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
state = TelephonyManager.CALL_STATE_IDLE;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
state = TelephonyManager.CALL_STATE_OFFHOOK;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
// Added this line to remove broadcast from caller application
// abortBroadcast();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start) {
}
protected void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
protected void onMissedCall(Context ctx, String number, Date start) {
}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if (lastState == state) {
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
} else if (isIncoming) {
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
class PhoneStateListener extends PhoneStateListener {
//private static final String TAG = "PhoneStateChanged";
Context context; //Context to make Toast if required
public PhoneStateListener(Context context) {
super();
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.DATA_CONNECTED:
LogUtil.debug(TAG, "Data connected send broadcast");
Intent dataConnectedIntent = new Intent(PhoneCallTimerService.DATA_CONNECTED);
context.sendBroadcast(dataConnectedIntent);
break;
case TelephonyManager.DATA_DISCONNECTED:
LogUtil.debug(TAG, "Data disconnected send broadcast");
Intent dataDisConnectedIntent = new Intent(PhoneCallOutgoingService.DATA_DISCONNECTED);
context.sendBroadcast(dataDisConnectedIntent);
break;
default:
break;
}
}
}
}
public class CallReceiver extends PhoneCallReceiver {
private static final String TAG = "CallReceiver";
#Override
protected void onIncomingCallStarted(Context ctx, String number, Date start) {
}
#Override
protected void onOutgoingCallStarted(final Context ctx, final String number, Date start) {
LogUtil.debug(TAG, "Outgoing call started from :: " + number);
final String name = Utils.getContactName(ctx, number);
Handler outgoingCallHandler = new Handler();
outgoingCallHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!Utils.isMyServiceRunning(PhoneCallOutgoingService.class, ctx) && !Utils.isMyServiceRunning(PhoneCallTimerService.class, ctx)) {
Intent outGoingCallService = new Intent(ctx, PhoneCallOutgoingService.class);
if (name != null && name.length() > 0) {
outGoingCallService.putExtra(CallReceiver.CALLER_NUMBER, name);
} else {
outGoingCallService.putExtra(CallReceiver.CALLER_NUMBER, number);
}
ctx.startService(outGoingCallService);
} else {
LogUtil.error(TAG, "Outgoing call service already started");
}
}
}, 2000);
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
LogUtil.debug(TAG, "Incoming call end from :: " + number);
Intent callTerminatedIntent = new Intent(ACTION_CALL_TERMINATED);
ctx.sendBroadcast(callTerminatedIntent);
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
LogUtil.debug(TAG, "Outgoing call ended from :: " + number);
Intent dataDisConnectedIntent = new Intent(PhoneCallOutgoingService.DATA_DISCONNECTED);
ctx.sendBroadcast(dataDisConnectedIntent);
}
#Override
protected void onMissedCall(Context ctx, String number, Date start) {
LogUtil.debug(TAG, "Missed call from :: " + number);
Intent missedCallIntent = new Intent(ACTION_CALL_MISSED);
ctx.sendBroadcast(missedCallIntent);
}
Of-course there is some code which is not important for your app so please comment or delete just delete that line.
I have Developing Application of Full Caller Id. In that dynamic screen call at the time of Incoming call / After Missed Call. Now this is work one time. When i received call. Than after it is not work or Not call any dynamic screen at the time Incoming call/ Missed call.
I have very confuse about my problem.
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.v("idle state", "CALL_STATE_IDLE");
// CALL_STATE_IDLE;
if(ring == true && callReceived == true && CheckMissCall.isReject == true)
{
Intent inter = new Intent(c, callLog.class);
inter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(inter);
}
if (ring == true && callReceived == false && CheckMissCall.isRunning== false) {
Log.v("missed call", "Missed call from : " + incomingNumber);
if(CheckMissCall.isShown)
{
c.stopService(new Intent(c, Unlock_hud.class));
}
flag = true;
if (prefs.getBoolean("main_state", true))
{
Intent inter = new Intent(c, MissCall.class);
inter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
inter.putExtra("CellNumber", incomingNumber);
c.startActivity(inter);
}
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// CALL_STATE_OFFHOOK;
callReceived = true;
Log.v("call received", "CALL_STATE_OFFHOOK " + incomingNumber);
break;
case TelephonyManager.CALL_STATE_RINGING:
ring = true;
// CALL_STATE_RINGING
Log.v("call ringing", "CALL_STATE_RINGING " + incomingNumber);
Log.d("flags", "flags: " + flag);
if (flag) {
//cut = true;
//flag = false;
CheckMissCall call = new CheckMissCall(c);
call.setName(incomingNumber);
call.setNumber4Sms(incomingNumber);
call.setContactPhoto();
Log.d("main", "state ringing");
//prefs = PreferenceManager.getDefaultSharedPreferences(c);
if (!prefs.getBoolean("main_state", false)) {
return;
}
/* if (!isScreenOn && CheckMissCall.isRunning) {
return;
}*/
if (CheckMissCall.isRunning) {
return;
}
else {
Log.d("main", "EEEEEEEEEEEEEEEE: Unlock hud");
Intent in = new Intent(c, Unlock_hud.class);
in.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
c.startService(in);
// c.stopService(new Intent(c, Unlock_hud.class));
}
}
break;
}
this is because when any call comes your app goes into background, while for the first time when you receive call your MyPhoneStateListener listens for the call and it ends..
now do one thing.. Run your code in service it will run in background and it will call your dynamic screen
in your main activity start service for this i have used toggle button(to enable or disable service)
tgl_switch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(tgl_switch.isChecked()){
startService(new Intent(getApplicationContext(),LogsService.class));
Toast.makeText(getApplicationContext(), "Call Logger Active",
Toast.LENGTH_SHORT).show();
}else{
stopService(new Intent(getApplicationContext(),LogsService.class));
Toast.makeText(getApplicationContext(), "Call Logger Deactive",
Toast.LENGTH_SHORT).show();
}
}});
for example i did this
public class LogsService extends Service {
String name;
String phNumber;
String callType;
String callDate;
Date callDayTime;
String callDuration;
String dir ;
String fileName;
boolean wasRinging=false, wasoffHook=false, wasidle=false;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// This code will execute when the phone has an incoming call
Log.d("ring ", "Detected");
wasRinging = true;
// get the phone number
// String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
// Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)){
wasoffHook=true;
// Toast.makeText(context, "hang up", Toast.LENGTH_LONG).show();
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
// This code will execute when the call is disconnected
wasidle=true;
// Toast.makeText(context, "IDLE STATE", Toast.LENGTH_LONG).show();
if((wasRinging && wasoffHook && wasidle)){
// this is received call event
startActivity(new Intent(getApplicationContext(), Incoming.class));
} else if(wasRinging && wasidle){
// this is missed call event
startActivity(new Intent(getApplicationContext(), MissCall.class));
}
wasidle = false;
wasoffHook = false;
wasRinging=false;
}
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
IntentFilter filter = new IntentFilter();
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
}
}
i used this code to get details of last call you can modify it in your way
I have a project in Android using blocking a call and send sms back to the caller.
I search all here. But those codes not working. I need help.
I am using Android 2.2
Use this ex for sms manager
Button bttsendsms;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bttsendsms =(Button)findViewById(R.id.button1);
bttsendsms.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Toast.makeText(SmsActivity.this, "hello", 6000).show();
sendSMS("5556","hello friends");
sendSMS("5558","hello friends");
}
});
}
private void sendSMS(String phoneNumber,String message)
{
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage(phoneNumber,null,message,null,null);
}
}
try this code it....this is working working for me i am developing same application.
use this code in oncreate method.
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// React to incoming call.
// number = PhoneNumberUtils.formatNumber(incomingNumber);
number = incomingNumber;
// If phone ringing
if (state == TelephonyManager.CALL_STATE_RINGING) {
new LoadStuff().execute(incomingNumber, message);
boolean isEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
if (!isEnabled) {
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,
isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
}
}
}
// If incoming call received
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
boolean isEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
if (isEnabled) {
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0
: 1);
// Post an intent to reload
Intent intent = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
}
}
}
};
telephonyManager.listen(callStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
and use this code outside oncreate method
public class LoadStuff extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
String number = params[0];
String message = params[1];
boolean error = false;
try {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, message, null, null);
} catch (IllegalArgumentException e) {
error = true;
}
if (error) {
Toast.makeText(getBaseContext(), "SMS SENDING FAILED",
Toast.LENGTH_SHORT).show();
}
return null;
}
}