标签:
最近在做一个短信接收器的小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});
}
}
}
标签:
原文地址:http://www.cnblogs.com/bujiangjiu/p/4633736.html