我想在我的Android应用程序中自动删除某些SMS.因此,我有一种方法可以完全按照我的意愿行事.但是,它仅在我将应用程序从Eclipse直接部署到我的手机时才有效.然后它删除传入的短信.但是,如果从市场下载应用程序,则无效.但也没有错误.有人知道我如何解决这个问题,或者这只能在root设备上运行吗?
public void deleteSMS(Context context, String message, String number) {
try {
mLogger.logInfo("Deleting SMS from inbox");
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms,
new String[] { "_id", "thread_id", "address",
"person", "date", "body" }, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
if (message.equals(body) && address.equals(number)) {
mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
}
} while (c.moveToNext());
}
} catch (Exception e) {
mLogger.logError("Could not delete SMS from inbox: " + e.getMessage());
}
}
最佳答案
实际上,我的帖子中的代码是100%正确的.问题是Android收到短信需要一些时间来存储短信.所以解决方案是只添加一个处理程序并将删除请求延迟1或2秒.
这实际上解决了整个问题.
编辑(感谢Maksim Dmitriev):
请注意,您无法在使用Android 4.4的设备上删除短信.
Also, the system now allows only the default app to write message data to the provider, although other apps can read at any time.
如果你尝试,不会抛出任何例外;什么都不会被删除.我刚刚在两个模拟器上测试过它.