Android Project Call Butler (5)-----Add monitoring Service

Source: Internet
Author: User
Tags set time

Above four, has implemented the interface design, blacklist (whitelist add and delete with blacklist same, no longer repeat), enable monitoring switch, Timer intercept switch, and interception mode selection function, the following will realize the most core function of call Butler, that is, interception function.

Main ideas :

1. Set up the interception mode, there are mainly two, one is the blacklist mode, that is, to intercept only the number in the blacklist, and the other is the white list mode, to intercept the number except the whitelist.

2. According to user's custom setting information, make regular expression, judge the standard of interception.

3. Use the corresponding class to implement the function of hanging up the phone.

The monitoring module mainly uses the service realization function, in order to realize the telephone hangs the function, here needs to call the remote Aidl Service, most books introduced to the Android source code in the following two files to copy to the corresponding location of the project:

The itelephony.aidl under the Com.android.internal.telephony bag

The neighboringcellinfo.aidl under the Android.telephony bag

But download the source need to turn over the wall, a bit of trouble, in fact, to do these purposes is to automatically generate Itelephony.java source files in the root directory, so there is no source code can also, the concrete practice is as follows:

1) under the SRC Directory of the project, create a new package:com.android.internal.telephony

2) under new package, create a new file named Itelephony.aidl.

3) Copy the following code into the newly created file.

  Package com.android.internal.telephony;          Interface itelephony{              boolean endcall ();              void Answerringingcall ();          }  

In this way, ADT automatically generates the Itelephony.java source file under the root directory.

The entire code for the service is as follows, and there are explanations:

Listenservice.java

Package Com.example.callmanager;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.text.simpledateformat;import Java.util.date;import android.app.Activity; Import Android.app.service;import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.database.cursor;import android.database.sqlite.SQLiteDatabase; Import Android.media.audiomanager;import Android.net.uri;import Android.os.ibinder;import Android.os.remoteexception;import Android.provider.contactscontract.phonelookup;import Android.telephony.phonestatelistener;import Android.telephony.telephonymanager;import Android.widget.Toast; Import Com.android.internal.telephony.itelephony;public class Listenservice extends Service {Telephonymanager Tmanager;private sqlitedatabase db;private sharedpreferences spf;private customphonecalllistener callListener;@    overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); SysTem.out.println ("Create");} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method Stubtmanager = (T    Elephonymanager) Getsystemservice (Telephony_service); Calllistener = new Customphonecalllistener (), SPF = this.getsharedpreferences ("setting", activity.mode_private); Tmanager.listen (Calllistener, phonestatelistener.listen_call_state); System.out.println ("Start"); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); calllistener = Null;tmanager = null ; System.out.println ("Destory"); Stopself ();} @Overridepublic boolean onunbind (Intent Intent) {//TODO auto-generated method Stubreturn Super.onunbind (Intent);} Create or Open database public void create_db () {//Create or Open database db = Sqlitedatabase.openorcreatedatabase (ListenService.this.getFil    Esdir (). toString () + "/LIST.DB3", null);   if (db = = null) {Toast.maketext (listenservice.this, "Database creation unsuccessful", Toast.length_long). Show (); else{/*//creates another table to hold the incoming call information Db.execsql ("CREATE table if not exists callinfo (_id integer PRIMARY key autoincr Ement, "+" name varchar (+), "+" number varchar (+), "+" calltimes varchar (20)); */}}//Insert public void Insert_callinfo (String name,string number,string time) {cursor cursor = DB.RAWQ    Uery ("select * from callinfo where calltimes = '" +time+ "';", null); if (cursor.getcount () = = 0) {db.execsql ("INSERT into Callinfo (name,number,calltimes) VALUES ('" + name+ "', '" + number + "'    , ' + Time + ');        } cursor.close (); } public class Customphonecalllistener extends phonestatelistener{@Override public void oncallstatechanged (int stat        E, String incomingnumber) {super.oncallstatechanged (state, Incomingnumber);    if (Spf.getboolean ("Isstartlisten", False)) {//Determine if the phone is create_db () in the blacklist;    Boolean callend_flag = false;    String incomingname = null; SimpleDateFormat formatter = new SimpleDateFormat ("Mm-dd Hh:mm "); Date curdate = new Date (System.currenttimemillis ());//Get current time String strtime = Formatter.format (Curda    TE);    If you enable the whitelist mode if (Spf.getboolean ("Iswhitelist", False)) {System.out.println ("whiteList");        Callend_flag =!isinwhitelist (Incomingnumber);        Find contact name by number Incomingname = Getcontactsnamebynumber (Incomingnumber);    }//If it is a blacklist mode else{Incomingname = Isinbalcklist (Incomingnumber);    if (Incomingname = = null) Callend_flag = FALSE;    else Callend_flag = true;    }//If the time period is enabled, determine if the current call time is in the set time period if (Spf.getboolean ("Istime", False)) {System.out.println ("inTime");    Callend_flag = Callend_flag && isintercepttime (strtime);    } switch (state) {case TelephonyManager.CALL_STATE_IDLE:break;    Case TelephonyManager.CALL_STATE_OFFHOOK:break;        Case TelephonyManager.CALL_STATE_RINGING:toggleRingerMute (Getapplicationcontext ()) When the phone is being called;            if (Callend_flag) {        try {method = Class.forName ("Android.os.ServiceManager"). GetMethod ("GetService", string.class);//Get remote Teleph Ony_service agent for Ibindler object IBinder binder = (ibinder) method.invoke (null, New Object[]{telephony_service});//    Convert the agent of the IBinder object to the Itelephony object Itelephony telephony = ITelephony.Stub.asInterface (binder);//Hang Up the phone telephony.endcall (); } catch (Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (ClassNotFoundException  e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( InvocationTargetException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (RemoteException e) {//Todo A        Uto-generated catch Blocke.printstacktrace ();}    Insert the number into the call Information database//Get the current time if (incomingname = = null) {Incomingname = "unfamiliar number"; } inserT_callinfo (Incomingname, Incomingnumber, strtime);        } System.out.println ("Bindlisten");    Break    }} db.close ();  }//Find the name of the contact by phone number, if found, return the name of the contact, otherwise, return null public string Getcontactsnamebynumber (string number) {Cursor C             = Getcontentresolver (). Query (Uri.withappendedpath (Phonelookup.content_filter_uri, number), new string[] { phonelookup._id, Phonelookup.number, Phonelookup.display_name, phonelookup.t YPE, Phonelookup.label}, NULL, NULL, NULL);  if (c.getcount () = = 0) {return null;}         else {c.movetofirst (); Return c.getstring (2); Get name}} private static int previousmutemode =-1; /** * Call Mute * * @param context */private void Toggleringermute (context context) {Audiomanager am = (audiomanager     ) Context.getsystemservice (Context.audio_service);        if (Previousmutemode = =-1) {Previousmutemode = Am.getringermode (); Am.setringermode (0);     } am.setringermode (Previousmutemode); Previousmutemode =-1; }//Determine if the current dialing time is in the Intercept period public boolean isintercepttime (String time) {///If the period is enabled (Spf.getboolean ("Istime", false)) { String startTime = spf.getstring ("StartTime", "" "); String endTime = spf.getstring ("EndTime", "");//Compare whether the current time is within the intercept period if (Time.compareto (startTime) >= 0 &&    Time.compareto (EndTime) <= 0) {return true; }} return false; }//Determine if a given number is in the whitelist public boolean isinwhitelist (String phone) {cursor cursor = db.rawquery ("select * from WhiteList whe Re number= ' "+phone+" '; ", null); Cursor.movetofirst (); If the number is in the whitelist, true if (Cursor.getcount () > 0) {cursor.close (); return true;} return false; }//Determine if the given number is in the blacklist public string isinbalcklist (string phone) {cursor cursor = db.rawquery ("Select * from blacklist wher    E number= ' "+phone+" '; ", null);    String name = NULL;    Cursor.movetofirst (); if (Cursor.getcount () >0) name = Cursor.getstring (Cursor.getcolumnindex ("Name "));    Cursor.close (); return name; @Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;}}

Code is very long, but the core is Customphonecalllistener this part, the main idea is to read the user's settings information to determine whether to intercept.

It is also implemented here, the interception information is written to the database, so there is the code above the relevant code of the database.

Finally, the important point is that, like activity, the service also needs to be registered and added to the androidmanifest.xml:

<service android:name= "Com.example.callmanager.ListenService"     android:enabled= "true" >     < intent-filter>         <action android:name= "Com.example.callmanager.ListenService"/>      </ Intent-filter>  

Of course, because to listen to the status of incoming calls, but to read the call logs and read the status of the phone permission to add in the Androidmanifest.xml:

<uses-permission android:name= "Android.permission.READ_PHONE_STATE"/><uses-permission android:name= " Android.permission.CALL_PHONE "/>


This allows the service to be started by intent when the listener is required to be enabled, and when the service is enabled, it can be monitored even if it exits the activity, since the service is still running in the background, which is the most basic function of the service.

Android Project Call Butler (5)-----Add monitoring Service

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.