我尝试获取短信列表,下面的代码在某些设备上运行良好,但在其他设备上运行不佳。使用以下代码对四台设备进行了详细测试。
LG optimus one[android 2.2] - 运行良好。 SS galaxy s3[android4.0.4] - 运行良好。 SS 银河 s2[安卓 2.3.5] - 不工作。 SS galaxy s2[android 4.0.4] - 不工作。
似乎结果取决于设备而不是 android 版本,因为具有相同 android 版本 [4.0.4] 的两个设备显示不同。设备不工作的症状是 c.getCount() = 0 即使它们有很多短信。查询不返回任何内容。为什么是这些?我怎样才能获得 galaxy s2 中的短信列表?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String smsMsgBody = null;
String smsMsgAddress = null;
String smsMsgDirection = null;
Uri uri = Uri.parse("content://sms");
// Uri uri = Uri.parse("content://sms/inbox");
// Uri uri = Uri.parse("content://sms/conversations/");
Cursor c= getContentResolver().query(uri, null, null,null,null);
// startManagingCursor(c);
if (c.getCount() > 0)
{
String count = Integer.toString(c.getCount());
while (c.moveToNext())
{
smsMsgBody = c.getString(c.getColumnIndex("body"));
smsMsgAddress = c.getString(c.getColumnIndex("address"));
smsMsgDirection = c.getString(c.getColumnIndex("type"));
// Do things using above sms data
}
}
c.close();
}
最佳答案
content://sms/
是not a supported content provider .这是一种隐藏方法,可能并非在所有设备中都可用。在 Android 4.4 KitKat 设备中,您可以使用 this answer 中的代码这样做:
public List<String> getAllSms() {
List<String> lstSms = new ArrayList<String>();
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(Telephony.Sms.Inbox.CONTENT_URI, // Official CONTENT_URI from docs
new String[] { Telephony.Sms.Inbox.BODY }, // Select body text
null,
null,
Telephony.Sms.Inbox.DEFAULT_SORT_ORDER // Default sort order);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
lstSms.add(c.getString(0));
c.moveToNext();
}
}
else {
throw new RuntimeException("You have no SMS in Inbox");
}
c.close();
return lstSms;
}
我不相信现在有一种记录在所有设备上的方法。
关于android - 如何根据各种设备获取短信列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652200/