android studio短信提醒
时间: 2023-12-26 18:28:37 浏览: 171
以下是使用Android Studio实现短信提醒的示例代码:
```java
// 在AndroidManifest.xml文件中添加短信权限
<uses-permission android:name="android.permission.RECEIVE_SMS" />
// 在需要接收短信的Activity中注册BroadcastReceiver
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver smsReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建BroadcastReceiver实例
smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 获取短信内容
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null && pdus.length > 0) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
String messageBody = smsMessage.getMessageBody();
// 显示短信内容的Toast提示
Toast.makeText(context, messageBody, Toast.LENGTH_SHORT).show();
}
}
}
};
// 注册BroadcastReceiver
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册BroadcastReceiver
unregisterReceiver(smsReceiver);
}
}
```
这段代码实现了在Android Studio中接收短信并显示短信内容的功能。首先,在AndroidManifest.xml文件中添加了接收短信的权限。然后,在需要接收短信的Activity中注册了一个BroadcastReceiver,用于接收短信。在BroadcastReceiver的onReceive()方法中,获取短信内容并通过Toast显示出来。最后,在Activity的onDestroy()方法中取消注册BroadcastReceiver,以避免内存泄漏。
阅读全文