Android realizes the development of telephone interception and interception cue sound function _android

Source: Internet
Author: User
Tags reflection dialpad

The content of this article is in the Android system how to write the program to intercept the phone, and issued a blocking prompt to remind users, you can say this function is more practical.

1. Telephone interception

This function you may all know, is to use the principle of reflection invoke Itelephony hidden method to achieve.

2, after the interception prompt busy/empty number/shutdown/has been shut down

This function is actually to use MMI instructions, specifically how to set the call transfer designation can refer to here http://baike.baidu.com/view/206402.html?fromTaglist.

In this article we will use the "Encounter busy transfer" function. The way the Chinese move is set is **67# phone number #, the way to cancel is # #67 #. "Unconditional transfer" replaces 67 with 21. These two instructions can be entered directly in the phone's dial-up Interface and Dial test. Itelephony Endcall method hangs up the phone, will prompt the telephone to be busy. If you have set up a busy time to transfer to a blank/shutdown/Shutdown phone number, you will be prompted to dial the phone number is empty/shut down/has been down.

In fact, we can download the xxx guardian to see, it set up the call rejection mode, will start to set the MMI command interface. Then go to "set-> call settings-> call forwarding" to see "when the line is busy transfer" set the phone number, you can know the empty number/shutdown/downtime corresponds to what the phone number is.

1, modify the value of Blocked_number this variable, set it to the number you want to test the interception.

2, all functions in an activity to achieve, so we have to run the work, and then click "Set Call Transfer", set a good call transfer, do not close to this activity, closed to intercept the phone. A willing friend can write a service on his own. Run the interception function in the background.

Implementation Mode 1:

The code is as follows:

Package net.toeach.android.callforwarding;   
  
Import Java.lang.reflect.Method;   
Import android.app.Activity;   
Import Android.content.BroadcastReceiver;   
Import Android.content.Context;   
Import android.content.Intent;   
Import Android.content.IntentFilter;   
Import Android.media.AudioManager;   
Import Android.net.Uri;   
Import Android.os.Bundle;   
Import Android.os.Handler;   
Import Android.os.Message;   
Import android.os.RemoteException;   
Import Android.telephony.TelephonyManager;   
Import Android.util.Log;   
Import Android.view.View;   
  
Import Android.view.View.OnClickListener;   
  
Import Com.android.internal.telephony.ITelephony;  
 /** * Demonstrates how to set up call forwarding, an example of intercepting a phone (which prompts for an empty number after interception) * @author Tony from Toeach. * @email wan1976@21cn.com */public class Mainactivity extends activity {private static final String TAG = MainA   
    
 Ctivity.class.getSimpleName ();   
 Private final static int op_register = 100;   Private final static int op_cancel = 200;
   
 Private final static String Blocked_number = "1892501xxxx";//the number to intercept//when the line is busy, 13800000000 is an empty number, so you will be prompted to dial the number is empty   
  Private final String Enable_service = "tel:**67*13800000000%23";   
  
 Transfer private final String Disable_service = "tel:%23%2367%23" when busy;   
  Private Incomingcallreceiver Mreceiver;   
  Private Itelephony Itelephony;   
   
  Private Audiomanager Maudiomanager;   
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);   
      
    Setcontentview (R.layout.main);    
     Findviewbyid (r.id.btnenable). Setonclicklistener (New Onclicklistener () {public void OnClick (View v) {//Set call forwarding   
  Message message = Mhandler.obtainmessage ();   
  Message.what = Op_register;   
  Mhandler.dispatchmessage (message);   
      
    }   
    });   
       Findviewbyid (r.id.btndisable). Setonclicklistener (New Onclicklistener () {public void OnClick (View v) {//Cancel call forwarding Message message = MHANDLER.OBTAINMEssage ();   
    Message.what = Op_cancel;   
  Mhandler.dispatchmessage (message);   
      
    }   
    });   
 Mreceiver = new Incomingcallreceiver ();     
    Intentfilter filter = new Intentfilter ("Android.intent.action.PHONE_STATE"); Registerreceiver (mreceiver, filter)//Registration Broadcastreceiver Maudiomanager = (audiomanager) getsystemservice (C Ontext.   
      
    Audio_service); Using reflection to obtain hidden Endcall methods Telephonymanager telephonymgr = (telephonymanager) getsystemservice (Context.telephony_service)   
 ;   
  try {Method Getitelephonymethod = TelephonyManager.class.getDeclaredMethod ("Getitelephony", (class[)) null);   
  Getitelephonymethod.setaccessible (TRUE);   
   Itelephony = (itelephony) Getitelephonymethod.invoke (Telephonymgr, (object[)) null);   
   catch (Exception e) {e.printstacktrace (); } private Handler Mhandler = new Handler () {public void Handlemessage (message response) {int   
   what = Response.what; SwItch (what) {case op_register:{Intent i = new Intent (Intent.action_call);   
       I.setdata (Uri.parse (Enable_service));   
    StartActivity (i);   
    Break   
       Case op_cancel:{Intent i = new Intent (Intent.action_call);   
       I.setdata (Uri.parse (Disable_service));   
    StartActivity (i);   
    Break   
   
 }   
   }   
 }   
 }; Private class Incomingcallreceiver extends broadcastreceiver{@Override public void onreceive (context context, inte   
     NT Intent) {String state = Intent.getstringextra (telephonymanager.extra_state);   
       
  LOG.I (TAG, "state:" + state);   
     String number = Intent.getstringextra (Telephonymanager.extra_incoming_number);   
       
     LOG.D (TAG, "incomng number:" + number); if (State.equalsignorecase (telephonymanager.extra_state_ringing)) {//Telephone is ringing if (number.equals (Blocked_number)) {/ /intercept the specified phone number//First mute handle Maudiomanager.setringermode (Audiomanager.ringer_mode_silent);   
        
      LOG.D (TAG, "Turn ringtone silent");   
   try {//Hang up the phone itelephony.endcall ();   
   catch (RemoteException e) {e.printstacktrace ();   
     //Resume normal ringtones maudiomanager.setringermode (audiomanager.ringer_mode_normal);   }   
     }   
 }   
 }   
}

         Androidmanifest.xml is as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <manifest "xmlns:android=" Schemas.android.com/apk/res/android "package=" net.toeach.android.callforwarding "android:versioncode=" 1 "a"  
    Ndroid:versionname= "1.0" > <application android:icon= "@drawable/icon" android:label= "@string/app_name" > <activity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action android:n  
      Ame= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <uses-sdk android:minsdkversion= "8"/&  
    
  Gt <uses-permission android:name= "Android.permission.READ_PHONE_STATE"/> <uses-permission android:name= " Android.permission.CALL_PHONE "/> </manifest> 

Implementation Mode 2:

1, the establishment of package android.refusecalling.

The Refusecalling.java code is as follows:

Package android.refusecalling;   
Import android.app.Activity;   
Import Android.net.Uri;   
  
Import Android.os.Bundle;   
Import java.lang.reflect.InvocationTargetException;   
  
Import Java.lang.reflect.Method;   
Import Android.content.Context;   
Import android.content.Intent;   
Import android.os.RemoteException;   
Import Android.telephony.PhoneStateListener;   
Import Android.telephony.TelephonyManager;   
Import Android.util.Log;   
Import Android.widget.TextView;   
  
Import Com.android.internal.telephony.ITelephony;   
  public class Refusecalling extends activity {private static final String TAG = "Telephony";   
  Private TextView view = null;   
  Private Telephonymanager Tmanager = null;   
     
   Private Itelephony itelephony = null;   
   When the line is busy, the number that is dialed is the empty number private final String Enable_service = "tel:**67*13800000000%23";   
  When the line is busy, the prompt dial number is shutdown private final String enable_poweroff_service = "tel:**67*13810538911%23";   Transfer when the line is busy, the number that is dialed is an outage
  Private final String Enable_stop_service = "tel:**21*13701110216%23";   
  
  Transfer private final String Disable_service = "tel:%23%2321%23" when busy;   
       
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Turn on the listening phone function telephonymanager mtelephonymgr = (Telephonymanager) this. Getsystemservice (Context.telepho   
    Ny_service);   
       
    Mtelephonymgr.listen (New Telelistener (), phonestatelistener.listen_call_state);   
    GUI view = new TextView (this);   
    View.settext ("Listen the State of phone\n");   
       
    Setcontentview (view);   
    Tmanager = (Telephonymanager) this.getsystemservice (Context.telephony_service);   
    Initialize Itelephony Class <TelephonyManager> c = telephonymanager.class;   
    Method getitelephonymethod = null;   
    try {Getitelephonymethod = C.getdeclaredmethod ("Getitelephony", (class[)) null); Getitelephonymethod.Setaccessible (TRUE);   
    catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace ();   
    catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace ();   
    try {itelephony = (itelephony) Getitelephonymethod.invoke (Tmanager, (object[)) null);   
    catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();   
    catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();   
    catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace ();   
    }//Enable empty number hint Intent i = new Intent (Intent.action_call);   
    I.setdata (Uri.parse (Enable_stop_service));   
    StartActivity (i);   
  LOG.V (TAG, "Enable empty number hint"); Class Telelistener extends Phonestatelistener {@Override public void Oncallstatechanged (int state, String incomingnumber) {super.oncallstatechanged (state, Incomingnumber);   
        Switch (state) {case Telephonymanager.call_state_idle: {log.e (TAG, "Call_state_idle");   
        View.append ("call_state_idle" + "\ n");   
      Break   
        Case Telephonymanager.call_state_offhook: {log.e (TAG, "Call_state_offhook");   
        View.append ("Call_state_offhook" + "\ n");   
      Break   
        Case telephonymanager.call_state_ringing: {log.e (TAG, "call_state_ringing");   
        View.append ("call_state_ringing" + "\ n");             
        try {itelephony.endcall ();   
        catch (RemoteException E1) {//TODO auto-generated catch block E1.printstacktrace ();   
      } break;   
      } Default:break;   
    }} protected void OnStop () {super.onstop ();   
  }protected void OnDestroy () {Super.ondestroy ();   
    Finish ();   
    Intent i = new Intent (Intent.action_call);   
    I.setdata (Uri.parse (Disable_service));   
    StartActivity (i);   }   
}

2, the establishment of package android.telephony.

The NEIGHBORINGCELLINFO.AIDL code is as follows:

Package android.telephony;

3, the establishment of package com.android.internal.telephony.

The ITELEPHONY.AIDL code is as follows:

* * * * licensed under the Android License, Version 2.0 (the "License");  
 * You could not use this file, except in compliance with the License.  * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required By applicable or agreed into writing, software * Distributed under the License is distributed on ' as is ' basis  
 , * without warranties or CONDITIONS of any KIND, either express or implied.  
 * The License for the specific language governing permissions and * limitations under the License.   
  
* * Package com.android.internal.telephony;   
Import Android.os.Bundle;   
Import java.util.List;   
Import Android.telephony.NeighboringCellInfo; Import com.   
  
Framespeed.neighboringcellinfo; /** * Interface used to interact with the phone. Mostly this are used by the * Telephonymanager class.  
 A few places are still using this directly. * them up if possible and use TelepHonymanager Insteadl. * * {@hide}/interface Itelephony {/** * Dial a number. This is doesn ' t place the call.  
   IT Displays * the Dialer screen. * @param number The number is dialed.  
   If NULL, this * would display the Dialer screens with no number pre-filled.  
*/void Dial (String number);  
   /** * Place a call to the specified number.  
   * @param number The number is called.   
  
  */void Call (String number);  
   /** * If There is currently-a call-in-progress, show the call screen. * The DTMF Dialpad may or May is visible initially, depending on * whether it is up when the user last exited th  
   E Incallscreen.  
   * @return True if the call screen is shown.   
  
  * * Boolean showcallscreen (); /** * Variation of Showcallscreen () that also specifies whether the * DTMF Dialpad should is initially visible W  
   Hen the Incallscreen * comes up. * * @param Showdialpad if True, make the Dialpad visible initially, * Otherwise hide the dialpad initially.  
   * @return True if the call screen is shown.   
  
  * * @see Showcallscreen * * Boolean Showcallscreenwithdialpad (Boolean showdialpad);  
   /** * End Call if there be a call into progress, otherwise does nothing.   
  
  * * @return Whether it hung Up/boolean endcall ();  
   /** * Answer the currently-ringing call. * If there ' s already a is active call, then call'll be * automatically put on hold.  
   If both lines are currently in use, the * current active call would be ended. * * Todo:provide a flag to let the caller specify what policy to-use * if both lines. (The current behavior are hardwired to * "answer incoming, end ongoing", which are how the called button * is Specce  
   D to behave.) * * Todo:this should be a oneway call (especially since it's called * directly from the key Queue thread).   
  
  * * void Answerringingcall ();  
   /** * Silence the ringer if a incoming call is currently ringing.  
   * (If vibrating, stop the vibrator also.) * * It ' s safe to call this if the ringer has already been silenced, or * even if there ' no incoming call.  
   (If So, this method would do nothing.)  
   * * Todo:this should be a oneway call too (= above).  
   * (actually *all* the methods here This return void can * probably be oneway.)   
  
  * * void Silenceringer ();  
   /** * Check If we are in either a active or holding call * @return True if the phone is offhook.   
  
  * * Boolean isoffhook ();  
   /** * Check If an incoming phone, call, ringing or call waiting.  
   * @return True if the phone is ringing.   
  
  * * Boolean isringing ();  
   /** * Check If the phone is idle.  
   * @return True if the phone is IDLE.   
  
  * * Boolean isidle (); /** * ChEck to = If the radio is on or not.  
   * @return Returns TRUE if the radio is on.   
  
  * * Boolean isradioon ();  
   /** * Check if the SIM pin lock is enabled.  
   * @return True if the SIM pin lock is enabled.   
  
  * * Boolean issimpinenabled ();  
   /** * Cancels the missed calls notification.   
  
  * * void cancelmissedcallsnotification (); /** * Supply a PIN to unlock the SIM.  
   Blocks until a is determined.  
   * @param pin the pin to check.  
   * @return Whether the operation was a success.   
     
   * * Boolean supplypin (String pin); /** * [asd2-es1|   
  
  CONNICE|2011.04.14] */boolean Supplypuk (String puk, string pin); /** * Handles PIN MMI commands (PIN/PIN2/PUK/PUK2), which are initiated * without SEND (so <code>dial</  
   Code> is not appropriate).  
   * * @param dialstring the MMI command to be executed.  
   * @return True if MMI command is executed. * * Boolean handlePinmmi (String dialstring);  
   /** * Toggles the radio on or off.   
  
  * * void Toggleradioonoff ();   
  
  /** * Set "radio to" or off * * Boolean Setradio (Boolean turnon);   
  
  /** * Request to update location information in service state */void updateservicelocation ();  
   /** * Enable Location update notifications.   
  
  * * void enablelocationupdates ();  
   /** * Disable Location update notifications.   
  
  * * void disablelocationupdates ();  
   /** * Enable a specific APN type.   
  
  */int Enableapntype (String type);  
   /** * Disable a specific APN type.   
  
  */int Disableapntype (String type);  
   /** * Allow mobile data connections.   
  
  * * Boolean enabledataconnectivity ();  
   /** * Disallow mobile data connections.   
  
  * * Boolean disabledataconnectivity ();  
   /** * Whether data connectivity is possible. * * Boolean IsdataconnectivitypoSsible ();   
  
  Bundle getcelllocation ();  
   /** * Returns The neighboring cell information of the device.   
  
   * * list<neighboringcellinfo> getneighboringcellinfo ();   
   int getcallstate ();   
   int getdataactivity ();   
  
  int getdatastate ();  
   /** * Returns The current active phone type as Integer. * Returns TELEPHONYMANAGER.PHONE_TYPE_CDMA if Rilconstants.cdma_phone * and telephonymanager.phone_type_gsm if RILCon Stants.   
  
  Gsm_phone */int getactivephonetype ();   
  
  /** * Returns the CDMA ERI icon Index to display */int getcdmaeriiconindex ();   
  
  /** * Returns the CDMA ERI icon mode, * 0-on * 1-flashing/int getcdmaeriiconmode ();   
  
  /** * Returns The CDMA ERI text, */String getcdmaeritext ();  
   /** * Returns True if OTA service provisioning needs to run.  
   * Only relevant on some technologies, others'll always * return false.  
  */Boolean needsotaserviceprovisioning ();   
  
  /** * Returns The unread count of voicemails */int getvoicemessagecount ();   
     
  /** * Returns the network type */int getnetworktype ();   
/** * Return True if a ICC card is present * * Boolean hasicccard ();  } parcelable Neighboringcellinfo;

  4, Androidmanifest.xml code is as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <manifest "xmlns:android=" Schemas.android.com/apk/res/android "package=" android.refusecalling "android:versioncode=" 1 "Android:versio Nname= "1.0" > <uses-permission android:name= "Android.permission.READ_PHONE_STATE"/> <uses-permissi On android:name= "Android.permission.CALL_PHONE"/> <uses-permission android:name= "Android.permission.MODIFY_" Phone_state "/> <application android:icon=" @drawable/icon "android:label=" @string/app_name "> &  
        Lt;activity android:name= ". refusecalling" android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.cat" Egory. LAUNCHER "/> </intent-filter> </activity> </application> </manifest> 
    

I hope this article can help develop the development of Android phone applications friends, thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.