编写一段安卓代码,实现系统短信页面以及基本收发功能
时间: 2023-06-17 09:08:36 浏览: 54
以下是一个简单的安卓代码,实现系统短信页面以及基本收发功能:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
```
2. 创建一个 SmsActivity 类,用于显示短信页面:
```
public class SmsActivity extends AppCompatActivity {
private ListView smsListView;
private List<String> smsList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
smsListView = findViewById(R.id.sms_list_view);
readSms();
}
private void readSms() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String message = cursor.getString(cursor.getColumnIndex("body"));
smsList.add(message);
}
cursor.close();
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, smsList);
smsListView.setAdapter(adapter);
}
}
```
3. 在 res/layout 文件夹下创建 activity_sms.xml 布局文件:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/sms_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
```
4. 创建一个 SmsSender 类,用于发送短信:
```
public class SmsSender {
public static void sendSms(String phoneNumber, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
}
}
```
5. 在需要发送短信的地方调用 SmsSender.sendSms() 方法:
```
SmsSender.sendSms("phoneNumber", "message");
```
注意,phoneNumber 为接收方手机号码,message 为发送的短信内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)