获取短信对话/主题列表并在ListView中显示联系人的姓名,可以通过以下步骤实现:
下面是一个示例代码,演示如何实现上述功能:
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSIONS_REQUEST_READ_SMS = 1;
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);
// 检查读取短信权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED) {
// 请求权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_SMS},
PERMISSIONS_REQUEST_READ_SMS);
} else {
// 已有权限,获取短信对话列表
getSMSConversationList();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_SMS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 获取短信对话列表
getSMSConversationList();
} else {
// 没有权限,处理权限请求被拒绝的情况
}
}
}
private void getSMSConversationList() {
// 查询短信对话列表
Uri uri = Telephony.Sms.Conversations.CONTENT_URI;
String[] projection = {Telephony.Sms.Conversations._ID, Telephony.Sms.Conversations.MESSAGE_COUNT,
Telephony.Sms.Conversations.SNIPPET};
String sortOrder = Telephony.Sms.Conversations.DEFAULT_SORT_ORDER;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(uri, projection, null, null, sortOrder);
// 设置ListView的适配器
String[] from = {Telephony.Sms.Conversations.SNIPPET, ContactsContract.Contacts.DISPLAY_NAME};
int[] to = {android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(adapter);
}
}
请注意,上述代码中的权限请求部分需要在AndroidManifest.xml文件中添加相应的权限声明:
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
这样,当用户授予读取短信和联系人的权限后,应用将获取短信对话列表并在ListView中显示联系人的姓名。
领取专属 10元无门槛券
手把手带您无忧上云