How Android uses broadcastreceiver backstage to monitor incoming call records

Source: Internet
Author: User
Tags date final sqlite

Android How to use Broadcastreceiver background to realize the interception of call records and access to the Sqllite database through Contentprovilder implementation interface

Broadcastreceiver is one of the four major Android components, essentially a global listener for listening to global broadcast messages. The following implementation of the background monitoring Android phone call records. This demo is divided into two programs, the first program is to set up the listener, then the simulation reset will have a global service in the background to monitor your caller ID, most of the call management software is so dry, the second project is to obtain call records, because just do a small experiment, so is based on a project changed , which involves some contentprivler knowledge, as well as a sqllite database, which is not meant to define the name.

First program code configuration file

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.android "android:versioncode=" 1 "android:versionname=" 1.0 "> <application android: icon= "@drawable/ic_launcher" android:label= "@string/app_name" > <service android:name= ". Ttactivity "> </service> <!--defines a broadcastreceiver, listening system boot broadcast--> <receiver Andro Id:name= ". Launchreceiver "> <intent-filter> <action android:name=" Android.intent.actio N.boot_completed "/> </intent-filter> </receiver> <provi Der Android:name=. " Dictprovider "android:authorities=" Org.crazyit.providers.dictprovider/> </application> <!--grant application access System boot Event permissions--> <uses-permission android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/> </manifest&
    
Gt /** * * * * * PACKAGe com.android;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
    
    
Import android.content.Intent; public class Launchreceiver extends Broadcastreceiver {@Override the public void onreceive (context context, Intent in
        Tent) {Intent tintent = new Intent (context, ttactivity.class);
    Start the specified service Context.startservice (tintent);
    
}/** * * */package com.android;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
    
    
Import Android.database.sqlite.SQLiteOpenHelper; public class Mydatabasehelper extends Sqliteopenhelper {final String create_table_sql = "CREATE TABLE dict" (_i
    d Integer PRIMARY key autoincrement, Word, detail) "; /** * @param context * @param name * @param version/Public mydatabasehelper-context, St
    ring name, int version) {Super (context, name, null, version);
  } @Override  The public void OnCreate (Sqlitedatabase db) {////The first time the database is used is automatically built Db.execsql (CREATE_TABLE_SQL); @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {System.out
    . println ("--------onUpdate called--------" + oldversion + "--->" + newversion);
    
    
}} package com.android;
Import java.io.FileNotFoundException;
Import Java.io.OutputStream;
Import Java.text.SimpleDateFormat;
    
    
Import Java.util.Date;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.os.IBinder;
Import Android.telephony.PhoneStateListener;
    
    
Import Android.telephony.TelephonyManager;
    public class Ttactivity extends Service {mydatabasehelper dbhelper;
    Telephonymanager Tmanager;
    SimpleDateFormat format=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");   String Word=format.format (New Date ());     
    @Override public IBinder onbind (Intent Intent) {return null; @Override public void OnCreate () {Tmanager = (Telephonymanager) getsystemservice (C Ontext.
        Telephony_service);
            DBHelper = new Mydatabasehelper (This, "mydict.db3", 1);
                Create a call status listener phonestatelistener listener = new Phonestatelistener () {@Override
                    public void oncallstatechanged (int state, String detail) { Switch (state) {//no status case Telephonymana Ger.
                        Call_state_idle:break;
                        Case TelephonyManager.CALL_STATE_OFFHOOK:break; Case TelephonyManager.CALL_STATE_RINGING:OutputStream o when caller bell ringss = null;
                            try {os = openfileoutput ("Phonelist", mode_append);
                                catch (FileNotFoundException e) {
                            E.printstacktrace (); 
} insertdata (Dbhelper.getreadabledatabase (), Word, detail);
PrintStream PS = new PrintStream (OS); Future electrical number recorded in the File//ps.println (new Date () + "Caller:" + incomingnum
ber);
                            Ps.close ();
                        Break
                    Default:break;
                } super.oncallstatechanged (State, detail);
            }
            };
    Monitor phone call status change Tmanager.listen (listener            , phonestatelistener.listen_call_state);
            } private void InsertData (Sqlitedatabase db, String Word, string detail) {//Execute INSERT statement
                Db.execsql ("INSERT into dict values (null,?,?)"
        , new String[]{word, detail});
            @Override public void OnDestroy () {Super.ondestroy (); Close the Mydatabasehelper sqlitedatabase if (dbhelper!= null) {Dbhelper.close () when exiting the program
            ;
    
}}/** * * */package com.android;
Import Android.net.Uri;
    
Import Android.provider.BaseColumns; /** * @version 1.0 */Public final class Words {//define authority public static final String AUT for this ContentProvider
    hority = "Org.crazyit.providers.dictprovider";  Define a static internal class public static final class Word implements Basecolumns {//define 3 data columns public for the actions allowed by the content Final static String _id= "_id";
        Public final static String word = "word";
        Public final static String DETAIL = "DETAIL"; Defines the two URI public final static URI Dict_content_uri = Uri.parse ("content://" + Authorit) that provides services for this CONTENT
        Y + "/words");        
    Public final static Uri Word_content_uri = Uri.parse ("content://" + Authority + "/word"); }
}
/** * * * * * * Package com.android;
Import Android.content.ContentProvider;
Import Android.content.ContentUris;
Import android.content.ContentValues;
Import Android.content.UriMatcher;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
    
Import Android.net.Uri;
        /** * @version 1.0 */public class Dictprovider extends ContentProvider {private static urimatcher Matcher
    = new Urimatcher (urimatcher.no_match);
    private static final int WORDS = 1;
    private static final int WORD = 2;
    Private Mydatabasehelper Dbopenhelper;
        static {//for Urimatcher registered two URI Matcher.adduri (words.authority, "Words", Words);
    Matcher.adduri (words.authority, "word/#", word); //The first time the Dictprovider is invoked, the system first creates the Dictprovider object and recalls the method @Override public boolean onCreate () {Dbopenhe
        Lper = new Mydatabasehelper (This.getcontext (), "mydict.db3", 1);
    return true; ///Insert Data method @Override public UrI insert (URI uri, contentvalues values) {//Get database instance sqlitedatabase db = Dbopenhelper.getreadabledatab
        ASE ();
        Insert data, return row ID long rowId = Db.insert ("Dict", words.word._id, values); If insert successfully returns URI if (RowId > 0) {//Append ID data uri after existing URI Worduri = Contenturis.
            Withappendedid (URI, rowId);
            The notification data has changed GetContext (). Getcontentresolver (). Notifychange (Worduri, NULL);
        return Worduri;
    return null; ///Delete data method @Override public int Delete (URI Uri, String selection, string[] selectionargs) {Sqli
        Tedatabase db = Dbopenhelper.getreadabledatabase ();
        Record the number of records deleted int num = 0;
        Matches a URI. Switch (Matcher.match (URI)) {Case words:num = Db.delete ("Dict", Selection, selection
                Args);
            Break
           Case WORD://Resolve the record ID that you want to delete     Long id = Contenturis.parseid (URI);
                String where = words.word._id + "=" + ID;
                    If the original WHERE clause exists, the concatenation WHERE clause if (selection!= null &&!selection.equals ("")) {
                where = where + "and" + selection;
                num = Db.delete ("Dict", where, Selectionargs);
            Break
        Default:throw New IllegalArgumentException ("Unknown URI:" + uri);
        //Notification data has changed GetContext (). Getcontentresolver (). Notifychange (URI, NULL);
    return num; ///Modify data method @Override public int update (URI uri, contentvalues values, String selection, string[] Sel
        Ectionargs) {Sqlitedatabase db = Dbopenhelper.getwritabledatabase ();
        Record the number of records modified int num = 0; Switch (Matcher.match (URI)) {Case words:num = db.update ("Dict", values, selection, s
     Electionargs);           Break
                Case WORD://Parse out the record ID that you want to modify long id = Contenturis.parseid (URI);
                String where = words.word._id + "=" + ID;
                    If the original WHERE clause exists, the concatenation WHERE clause if (selection!= null &&!selection.equals ("")) {
                where = where + "and" + selection;
                num = db.update ("Dict", values, where, Selectionargs);
            Break
        Default:throw New IllegalArgumentException ("Unknown URI:" + uri);
        //Notification data has changed GetContext (). Getcontentresolver (). Notifychange (URI, NULL);
    return num; ///Query data @Override public Cursor query (URI uri, string[] projection, String selection, string[] se
        Lectionargs, String sortOrder) {sqlitedatabase db = Dbopenhelper.getreadabledatabase ();
            Switch (Matcher.match (URI)) {case WORDS:    Execute Query return db.query ("Dict", projection, selection, Selectionargs, NULL, NULL,
            SortOrder);
                Case WORD://Parse out the record ID that you want to query long id = Contenturis.parseid (URI);
                String where = words.word._id + "=" + ID; If the original WHERE clause exists, the stitching WHERE clause if (selection!= null &&! "".
                Equals (selection)) {where = where + "and" + selection;
            Return Db.query ("Dict", projection, where, Selectionargs, NULL, NULL, sortOrder);
        Default:throw New IllegalArgumentException ("Unknown URI:" + uri); }//Returns the MIME type of the data corresponding to the specified Uri parameter @Override public String getType (URI uri) {switch (Matcher.match) ( URI) {//If the operation of the data is multiple records case Words:return "Vnd.android.cursor.dir/org.cra
                Zyit.dict "; If you screwThe data is a single record case Word:return "Vnd.android.cursor.item/org.crazyit.dict";
        Default:throw New IllegalArgumentException ("Unknown URI:" + uri); }
    }
}

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.