利用ContentResolver,点击查看短信按钮,读取Android系统的短信内容,并显示在Listview列表中,查看源码
时间: 2024-03-25 21:35:40 浏览: 153
以下是一个简单的例子,演示如何通过ContentResolver读取短信内容并显示在ListView中。
1. 首先,在AndroidManifest.xml文件中添加以下权限:
```
<uses-permission android:name="android.permission.READ_SMS"/>
```
2. 在布局文件中添加一个ListView控件:
```
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
3. 在Activity中获取ListView对象,并创建一个SimpleCursorAdapter对象:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String[] from = new String[]{"address", "body"};
int[] to = new int[]{android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
listView.setAdapter(adapter);
}
}
```
4. 使用ContentResolver查询短信数据,并将查询结果赋值给Cursor对象:
```
public class MainActivity extends AppCompatActivity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
Uri uri = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "body"};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
adapter.swapCursor(cursor);
}
}
```
5. 将Cursor对象与SimpleCursorAdapter对象关联,将查询结果显示在ListView中:
```
public class MainActivity extends AppCompatActivity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
adapter.swapCursor(cursor);
}
}
```
完整的代码示例如下:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String[] from = new String[]{"address", "body"};
int[] to = new int[]{android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
listView.setAdapter(adapter);
Uri uri = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "body"};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
adapter.swapCursor(cursor);
}
}
```
阅读全文