android如何使用BroadcastReceiver后台实现来电通话记录的监听并存取到sqllite数据库通过Contentprovilder实现接口
BroadcastReceiver 是android四大组件的一个,本质上是一种全局的监听器 ,用于监听全局的广播消息。下面实现了后台监听android手机通话记录。本demo 分两个程序,第一个程序是设置监听器,然后模拟器重启后就会有一个全局的 service在后台监听你的来电显示,大多数通话管理软件都是这么干的,第二个项 目是获取通话记录的,由于只是做一个小实验,所以是根据某个项目改的,里面 涉及到一些ContentPrivler的知识,还有sqllite数据库,里面定义名称并非其意 思。
第一个程序代码配置文件
<?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> <!-- 定义一个BroadcastReceiver,监听系统开机广播 --> <receiver android:name=".LaunchReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <provider android:name=".DictProvider" android:authorities="org.crazyit.providers.dictprovider"/> </application> <!-- 授予应用程序访问系统开机事件的权限 --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> </manifest> /** * */ package com.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class LaunchReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent tIntent = new Intent(context , TtActivity.class); // 启动指定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(_id integer primary key autoincrement , word , detail)"; /** * @param context * @param name * @param version */ public MyDatabaseHelper(Context context, String name, int version) { super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { // 第一个使用数据库时自动建表 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 (Context.TELEPHONY_SERVICE); dbHelper = new MyDatabaseHelper(this , "myDict.db3" , 1); // 创建一个通话状态监听器 PhoneStateListener listener = new PhoneStateListener() { @Override public void onCallStateChanged(int state , String detail) { switch (state) { // 无任何状态 case TelephonyManager.CALL_STATE_IDLE: break; case TelephonyManager.CALL_STATE_OFFHOOK: break; // 来电铃响时 case TelephonyManager.CALL_STATE_RINGING: OutputStream os = null; try { os = openFileOutput("phoneList", MODE_APPEND); } catch (FileNotFoundException e) { e.printStackTrace(); } insertData(dbHelper.getReadableDatabase() , word , detail); // PrintStream ps = new PrintStream(os); // // 将来电号码记录到文件中 // ps.println(new Date() + " 来电:" + incomingNumber); // ps.close(); break; default: break; } super.onCallStateChanged(state, detail); } }; //监听电话通话状态的改变 tManager.listen(listener , PhoneStateListener.LISTEN_CALL_STATE); } private void insertData(SQLiteDatabase db , String word , String detail) { //执行插入语句 db.execSQL("insert into dict values(null , ? , ?)" , new String[]{word , detail}); } @Override public void onDestroy() { super.onDestroy(); //退出程序时关闭MyDataBaseHelper里的SQLiteDatabase if (dbHelper != null) { dbHelper.close(); } } } /** * */ package com.android; import android.net.Uri; import android.provider.BaseColumns; /** * @version 1.0 */ public final class Words { // 定义该ContentProvider的Authority public static final String AUTHORITY = "org.crazyit.providers.dictprovider"; //定义一个静态内部类 public static final class Word implements BaseColumns { // 定义Content所允许操作的3个数据列 public final static String _ID = "_id"; public final static String WORD = "word"; public final static String DETAIL = "detail"; // 定义该Content提供服务的两个Uri public final static Uri DICT_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/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 { // 为UriMatcher注册两个Uri matcher.addURI(Words.AUTHORITY, "words", WORDS); matcher.addURI(Words.AUTHORITY, "word/#", WORD); } // 第一次调用该DictProvider时,系统先创建DictProvider对象,并回调该方法 @Override public boolean onCreate() { dbOpenHelper = new MyDatabaseHelper(this.getContext(), "myDict.db3", 1); return true; } // 插入数据方法 @Override public Uri insert(Uri uri, ContentValues values) { // 获得数据库实例 SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 插入数据,返回行ID long rowId = db.insert("dict", Words.Word._ID, values); // 如果插入成功返回uri if (rowId > 0) { // 在已有的 Uri的后面追加ID数据 Uri wordUri = ContentUris.withAppendedId(uri, rowId); // 通知数据已经改变 getContext().getContentResolver().notifyChange(wordUri, null); return wordUri; } return null; } // 删除数据的方法 @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 记录所删除的记录数 int num = 0; // 对于uri进行匹配。 switch (matcher.match(uri)) { case WORDS: num = db.delete("dict", selection, selectionArgs); break; case WORD: // 解析出所需要删除的记录ID long id = ContentUris.parseId(uri); String where = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (selection != null && !selection.equals("")) { where = where + " and " + selection; } num = db.delete("dict", where, selectionArgs); break; default: throw new IllegalArgumentException("未知Uri:" + uri); } // 通知数据已经改变 getContext().getContentResolver().notifyChange(uri, null); return num; } // 修改数据的方法 @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); // 记录所修改的记录数 int num = 0; switch (matcher.match(uri)) { case WORDS: num = db.update("dict", values, selection, selectionArgs); break; case WORD: // 解析出想修改的记录ID long id = ContentUris.parseId(uri); String where = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (selection != null && !selection.equals("")) { where = where + " and " + selection; } num = db.update("dict", values, where, selectionArgs); break; default: throw new IllegalArgumentException("未知Uri:" + uri); } // 通知数据已经改变 getContext().getContentResolver().notifyChange(uri, null); return num; } // 查询数据的方法 @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); switch (matcher.match(uri)) { case WORDS: // 执行查询 return db.query("dict", projection, selection, selectionArgs, null, null, sortOrder); case WORD: // 解析出想查询的记录ID long id = ContentUris.parseId(uri); String where = Words.Word._ID + "=" + id; // 如果原来的where子句存在,拼接where子句 if (selection != null && !"".equals(selection)) { where = where + " and " + selection; } return db.query("dict", projection, where, selectionArgs, null, null, sortOrder); default: throw new IllegalArgumentException("未知Uri:" + uri); } } // 返回指定uri参数对应的数据的MIME类型 @Override public String getType(Uri uri) { switch (matcher.match(uri)) { // 如果操作的数据是多项记录 case WORDS: return "vnd.android.cursor.dir/org.crazyit.dict"; // 如果操作的数据是单项记录 case WORD: return "vnd.android.cursor.item/org.crazyit.dict"; default: throw new IllegalArgumentException("未知Uri:" + uri); } } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, string
, broadcastreceiver
, uri
, 通话记录
, android 后台服务
, openfileoutput
, import
, public
, sqliteopenhelper
, java 解析 word
, sqlitedatabase
, selection
Android监听器
broadcastreceiver、broadcast receiver、broadcastreceiver类、view监听 broadcast、如何监听别人手机通话,以便于您获取更多的相关知识。