android 操作短信数据库
最近在做一个短信接收器的小demo,当有未读短信时,如果查看了该短信,则将该条短信在数据库中的状态改为已读。
刚开始在自己的app中用如下方法尝试的:
public void updateSmsToRead() {
android.util.Log.d("zzh-debug", " updateSmsToRead id = " + mId);
ContentValues values = new ContentValues();
values.put("read", "1");
values.put("seen", "1");
try {
String[] arg = {this.mId};
int result;
android.util.Log.d("zzh-debug", " before update sms");
result = MClock.getAppContext().getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=?", arg);
android.util.Log.d("zzh-debug", " result = " + result);
android.util.Log.d("zzh-debug", " after update sms");
} catch (Exception e) {
android.util.Log.d("zzh-debug", " update sms exception = " + e);
}
}
发现update不生效,但是query却是可以的,在网上查了很久后,发现有如下问题:
Other apps that are not selected as the default SMS app can only read the SMS Provider, but may also be notified when a new SMS arrives by listening for the SMS_RECEIVED_ACTION broadcast, which is a non-abortable broadcast that may be delivered to multiple apps. This broadcast is intended for apps that—while not selected as the default SMS app—need to read special incoming messages such as to perform phone number verification.
For more information about building SMS apps, read the blog post, Getting Your SMS Apps Ready for KitKat.
即只有默认短信应用才可以对短信数据库增删改,其他应用只能查询
如下是最后解决方案:
在我的应用中需要更新数据库的地方发送自定义广播给系统默认短信应用:
public void updateSmsToRead(String address, String body) {
Intent intent = new Intent("com.vanzotec.action.UPDATE_SMS");
intent.putExtra("sms_id", this.mId);
MClock.getAppContext().sendBroadcast(intent);
}
在系统短信中接收广播并更新数据库:
<receiver android:name=".util.MClockUpdateSmsReceiver">
<intent-filter>
<action android:name="com.vanzotec.action.UPDATE_SMS" />
</intent-filter>
</receiver>
package com.android.mms.util;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
public class MClockUpdateSmsReceiver extends BroadcastReceiver {
private static final String TAG = "MClockUpdateSmsReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.vanzotec.action.UPDATE_SMS")) {
String id = intent.getStringExtra("sms_id");
Log.d(TAG, " MClockUpdateSmsReceiver sms_id = " + id);
ContentValues values = new ContentValues();
values.put("read", "1");
values.put("seen", "1");
context.getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=?", new String[]{id});
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库