I've used the following code to disconnect a call programatically but It's not working.
private void callDisconnect(){
try{
TelephonyManager manager = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
Class c = Class.forName(manager.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
ITelephony telephony = (ITelephony)m.invoke(manager);
telephony.endcall();
} catch(Exception e){
Log.d("",e.getMessage());
}
}
Can anybody help me with this?? Do I need to change the code or something...??
For disconnecting a call programmatically you must add ITelephony.AIDL file in your project. If you have added it, then your package name must be com/android/internal/telephony/ITelephony.AIDL: for more information see Blocking Incoming call. Download the AIDL file from here.
To disconnect a call use endCall(); method of ITelephony
Simply use this broadcastreceiver. I tested it in one of my application and it works perfectly.
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, final Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL))
{
String phoneNumber = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);
if (phoneNumber.equals("123456"))
{
if (getResultData() != null)
{
setResultData(null);
}
}
}
}
}
It is not possible anymore in newer versions of android. The user decides when to end the call if it has already started. You can however block calls from happening.
You can block the outgoing call using the setResultData(null) function in the onReceive method of the Broadcast receiver.
public class BlockOutgoing extends BroadcastReceiver
{
String number;
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("12280", "asdasNumber is-->> " + number);
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
setResultData(null);
Toast.makeText(context, "Outgoing Call Blocked" , 5000).show();
}
}
<receiver
android:name=".BlockOutgoing"
android:label="#string/app_name" >
<intent-filter android:priority="1">
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
You cannot end a call like that in android 2.3+... using your code... I think only user can end his call...and for earlier versions You can see this link and This one
Related
I tried lot of links at so but I am not good enough to find the right code.I managed to block calls using this code.
public class BlockCallReceiver extends BroadcastReceiver{
Context context;
#Override
public void onReceive(Context context, Intent intent) {
Bundle myBundle = intent.getExtras();
if (myBundle != null)
{
System.out.println("--------Not null-----");
try
{
if (intent.getAction().equals("android.intent.action.PHONE_STATE"))
{
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
System.out.println("--------in state-----");
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
// Incoming call
String incomingNumber =intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
System.out.println("--------------my number---------"+incomingNumber);
// this is main section of the code,. could also be use for particular number.
// 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
ex.printStackTrace();
}
}
}
}
and in my Manifest
<receiver android:name=".utils.BlockCallReceiver" >
<intent-filter android:priority="100" >
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
It worked. But even the app is no in foreground/or not even in the active apps calls are blocked.
I tried to un register this BlockCallReceiver class in my Launcher Activity because I want to allow calls when the app is not open.
So in onPause I tried some codes given in answers but It did not work since my bad knowledge.
Here is an example that I tried but I'm stuck
ComponentName receiver = new ComponentName(MainActivity.this, BlockCallReceiver.class);
PackageManager pm = MainActivity.this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Please if someone can guide me to re allow calls when the app turns off I am really grateful.
Edit One :
If I use below
public void onPause() {
super.onPause();
MainActivity.this.unregisterReceiver(mybroadcast);
}
It throws me an error java.lang.IllegalArgumentException: Receiver not registered! Yes I have not registered it in my Activity only on that thing at the manifest. I know something is wrong but cannot understand it.
Edit Two : #Imen Nmn answer is helpful. I will try to register dynamically rather than the Manifest. But I have a doubt there should be someway with un registering B.receiver given in the Manifest ?
To Stop a broadcastReceiver , you should call : yourContext.unregisterReceiver(yourBroadcastReceiver);
if you notice this example , in onResume there is this.registerReceiver(the_receiver, filter); and in onPause , there is
this.unregisterReceiver(the_receiver);
Here an example :
public class Android Example extends Activity {
private BroadcastReceiver the_receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context c, Intent i) {
}
};
// Set When broadcast event will fire.
private IntentFilter filter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
// Register reciever if activity is in front
this.registerReceiver(the_receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
// Unregister reciever if activity is not in front
this.unregisterReceiver(the_receiver);
super.onPause();
}
}
As I can remember it, Avast anti-theft lets you set up a "secret pin" that you can dial in order to open up the UI. What happens when I dial it is that the call doesn't go through, then the dialer closes immediately and the UI opens up (or the UI goes above the dialer activity. I forgot).
I somehow implemented this, but instead of the call aborting, it goes to the background (green statusbar, ringing phone, etc.) while my activity goes in front of it.
How do I abort the call while opening up my own activity when I dial a specific number?
Some code on my approach:
Broadcast receiver for calls:
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Match if action is outgoing call.
Intent i = new Intent();
i.setAction(HelperClass.ACTION_NEW_OUTGOINGCALL);
i.setClassName(HelperClass.PACKAGE_NAME, HelperClass.CLASS_NAME_OUTGOING);
i.putExtra(HelperClass.CONTACT_KEY, "contact");
i.putExtra(HelperClass.CLIENT_DEVICE_KEY, "DUMMY");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
// Apparently, this doesn't work
abortBroadcast();
// --------------- FAILED ATTEMPT ---------------------
// if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
// TelephonyManager tm = (TelephonyManager) context
// .getSystemService(Context.TELEPHONY_SERVICE);
// try {
// // Java reflection to gain access to TelephonyManager's
// // ITelephony getter
// Log.v(HelperClass.TAG, "Get getTeleService...");
// Class c = Class.forName(tm.getClass().getName());
// Method m = c.getDeclaredMethod("getITelephony");
// m.setAccessible(true);
// com.android.internal.telephony.ITelephony telephonyService =
// (ITelephony) m.invoke(tm);
// } catch (Exception e) {
// e.printStackTrace();
// Log.e(TAG,
// "FATAL ERROR: could not connect to telephony subsystem");
// Log.e(TAG, "Exception object: " + e);
// }
}
}
}
Failed attempt: ITelephony not found. The failed attempt came from https://stackoverflow.com/a/5314372/3979290
UPDATE: Tried to implement, failed. Not sure how to implement: How to hang up outgoing call in Android?
Also viewed: How to abort an outgoing call after fixed seconds?
Update: Adding setResultData(null); to the broadcast receiver worked.
It immediately ended the call.
Sample:
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Immediately cancels the call since this sets the number to null.
setResultData(null);
// Launch activity here/other stuff you want to do
// Example:
// Intent i = new Intent(context, MyActivity.class);
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(i);
}
}
Manifest:
...
<receiver
android:name=".OutgoingCallReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
...
In my application I'am using BroadcastReceiver to track telephone state.
There are 3 states available in TelephonyManager.
EXTRA_STATE_IDLE
EXTRA_STATE_OFFHOOK
EXTRA_STATE_RINGING
In my scenario I want to show simple ui which shows some details about the caller while the phone is ringing and i want to close that ui when the call attended by user or call ended.
I'am calling my service when the phone state is Ringing. If my app is in use then I can see my ui part while the phone is ringing. If my app is not in use then I cant see the ui part.
I have checked in my background. The service is not running. I think my service is running only when my app is in use and it is not running when my app is not in use.
To overcome this what I should do?
This is my code.
#Override
public void onReceive(Context context, Intent intent) {
LoginActivity.login.finish();
MainActivity.main.finish();
telephonyRegister(context,intent);
}
public void telephonyRegister(final Context context, Intent intent)
{
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imeiSIM1= telephony.getDeviceId();
System.out.println("IMEI NUMBER"+imeiSIM1);
ctx=context;
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
try
{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)){
phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
isringing=true;
Intent intent11 = new Intent(ctx,ProjectDailogActivity.class);
intent11.putExtra("incoming_number",phoneNumber);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent11);
}
}
Manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<receiver android:name="com.domyhome.broadcastreceiver.IncomingCallInterceptor" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
I got the window like truecaller.
Just the values which i mentioned are default one.
But the same window is not coming when my app is not in use.
Please give me an idea.
that is why android developers invented the BroadcastReciever - it allows you to hook your code as a service in response for system events (such as boot, airplane mode, etc)
Vogella covers it very well: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
and for your situation (send commands as a response for the phone state) you can also use this article which provide a fully working example: http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61&aaid=86
article hightlights:
<!-- Manifest.xml -->
<receiver android:name=".IncomingCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
and in java - add these classes
//your Listener class:
private class MyPhoneStateListener extends PhoneStateListener
{
public void onCallStateChanged(int state, String incomingNumber)
{
// state = 1 means when phone is ringing
if (state == 1)
{
// do something
}
}
}
//Reciever class:
public class IncomingCall extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
// TELEPHONY MANAGER class object to register one listner
TelephonyManager tmgr = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
//Create Listner
MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
// Register listener for LISTEN_CALL_STATE
tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
No need to run it in a service just in the xml of your application in the reciever section use with phone ringing action and in your recieve implement your UI. and have a different reciever for your app to listen to when the phone is cut.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.e("onStartCommand", "onStartCommand");
return Service.START_STICKY;
}
http://developer.android.com/reference/android/app/Service.html
Use AlarmManager to activate service after a specific time and stop service and also kill AlarmManager when call came.
try like this,
AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
it will repeating while you manually not stopped it...may this helps you...
Hello guys i am trying to send two variables from an android service to a broadcast receiver, and i need help here..
i am setting up two var's in the oncreate method of the service class here..
#Override
public void onCreate() {
super.onCreate();
Intent eSendIntent = new Intent(getApplicationContext(), OutgoingCallReceiver.class);
eSendIntent.putStringArrayListExtra("BlockArray", contactsListB);
eSendIntent.putExtra("BlockBool", checkB);
getApplicationContext().sendOrderedBroadcast(eSendIntent, null);//Call receiver
}
and in my receiver class...
onReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
if(bundle == null)
return;
boolean cb = bundle.getBooleanExtra("BlockBool", true);
ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");
//disconnecting
try{
if(cb==false){
for(int ij = 0; ij < ab.size(); ij++){
if(ab.get(ij).contains(phonenumber)){
tempBoolean = true;
//Log.e("OutgoingCallReceiver", SmsBlockerService.contactsListB.get(ij));
}
}//for loop
if(tempBoolean==true){
setResultData(null);
Toast.makeText(context, phonenumber + " is Blocked", Toast.LENGTH_SHORT).show();
}
}else{
setResultData(null);
Toast.makeText(context, "All Out-Going Calls are Blocked", Toast.LENGTH_SHORT).show();
}//end of main if
} catch(Exception e){
Toast.makeText(context, "Detect Calls sample application Failed: ", Toast.LENGTH_LONG).show();
}
}
logcat:
E/BroadcastReceiver(1459): BroadcastReceiver trying to return result during a non-ordered broadcast
set this in your broadcast intent
i.setAction("MYACTION");
than set this in your manifest
<receiver android:name=".BroadcastClass" >
<intent-filter>
<action android:name="MYACTION" />
</intent-filter>
</receiver>
may be this should helpful
Assuming that you registered the receiver.Now try to make a small change:
boolean cb = bundle.getBooleanExtra("BlockBool", true);
ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");
Update:
In the on create... call the broadcast like...
sendOrderedBroadcast(eSendIntent);
You are facing that error because , setResultData() function works only with OrderedBroadcast.
From Android Documentation:
public final void setResultCode (int code)
Added in API level 1
Change the current result code of this broadcast; only works with broadcasts sent
through Context.sendOrderedBroadcast. Often uses the Activity RESULT_CANCELED and
RESULT_OK constants, though the actual meaning of this value is ultimately up to the
broadcaster.
This method does not work with non-ordered broadcasts such as those sent with
Context.sendBroadcast.
for broadcast receiver to work the activity/screen in which it is written should be up & running. so that receiver can receives the passed intent & it's value.
I've found a lot of pages about this in the web, but none of them helped me. I've been for hours stucked in this problem. That's why i decided to make my own question.
What I want to do is an application that receives an intent of the type ACTION_MEDIA_BUTTON and the method onReceive() of the Broadcastreceiver does something.
My Activity is like this:
public class MusicControlActivity extends Activity {
private MediaButtonIntentReceiver receiver = new MediaButtonIntentReceiver();
#Override
public void onCreate(Bundle p_SavedInstanceState) {
super.onCreate(p_SavedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(1000);
registerReceiver(receiver,filter);
}
#Override
public void onDestroy()
{
unregisterReceiver(receiver);
}
And my broadcastreceiver as follow:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver()
{
super();
}
#Override
public void onReceive(Context context, Intent intent)
{
String v_IntentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(v_IntentAction)) {
return;
}
KeyEvent v_Event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (v_Event == null) {
return;
}
int v_Action = v_Event.getAction();
if (v_Action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
The problem is that it doesn't work, no matter what I do. I've tried registering it dynamically with registerReceiver as in the code above. Also I've tried statically in the AndroidManifest.xml like this:
<receiver android:name=".MediaButtonIntentReceiver" android:enabled="true">
<intent-filter android:priority="10000000">
<action android:name="android.intent.action.ACTION_MEDIA_BUTTON" />
</intent-filter>
</receiver>
And as you can see I've set the priority to a high level and even though it doesn't work.
I've been on this for the whole day and I don't know what to do. The method onReceive from the broadcastreceiver isn't called anytime.
Does anyone know what should I do?
Use android.intent.action.MEDIA_BUTTON Instead in your manifest. Check : http://developer.android.com/training/managing-audio/volume-playback.html
First, you should stop using Toast as your diagnostic test. Use the Log class to log to LogCat, or breakpoints, or something.
Next, you should get rid of your MediaButtonIntentReceiver constructor, as it is not needed.
Then, I would dump the if (!Intent.ACTION_MEDIA_BUTTON.equals(v_IntentAction)) block, since it is also not needed.
Next, I would make sure that your media button actually works. Does it control other applications, like a music player? It may be that your media button is not Android-compliant or something.