c# - 发送短信时如何获取信息?
问题描述
我想知道用户接收/发送短信时的信息。为此,我创建了一个 SmsWatcher 类。
using AeroMobile.Utility.Helper;
using Android.App;
using Android.Content;
using Android.Provider;
[BroadcastReceiver]
[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED", "android.intent.action.SENDTO", "android.provider.Telephony.SMS_DELIVER" }, Priority = (int)IntentFilterPriority.HighPriority)]
public class SmsWatcher : BroadcastReceiver
{
public override async void OnReceive(Context context, Intent intent)
{
if (intent.Action != null)
{
if (intent.Action.Equals(Telephony.Sms.Intents.SmsReceivedAction))
{
var msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
foreach (var msg in msgs)
{
//incoming message
}
}
if (intent.Action.Equals(Telephony.Sms.Intents.SmsDeliverAction))
{
var msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
foreach (var msg in msgs)
{
//outgoing message
}
}
}
}
}
我在 MainActivity 中注册了这个广播服务,如下所示:
//starting SMS watcher service
var smsWatcherIntent = new Intent(ApplicationContext, typeof(SmsWatcher));
SendBroadcast(smsWatcherIntent);
上面的代码完全适用于传入消息,但不适用于传出消息。当用户发送短信时,您能否帮助我获取信息,例如我收到的传入消息的信息?
解决方案
根据这个答案的灵感
似乎从BroadcastReceiver
. 因此,阅读 SMS 的最佳方式是通过光标从 Android 数据库中读取。
下面是代码片段Xamarin.Android
:
private async Task CheckAndUpdateSms(Context context)
{
string lastReadTimeMilliseconds = Application.Current.Properties["LastSmsReadMilliseconds"].ToString();
ICursor cursor = context.ContentResolver.Query(Telephony.Sms.ContentUri, null, "date > ?", new string[] { lastReadTimeMilliseconds }, null);
if (cursor != null)
{
int totalSMS = cursor.Count;
if (cursor.MoveToFirst())
{
double maxReceivedTimeMilliseconds = 0;
for (int j = 0; j < totalSMS; j++)
{
double smsReceivedTimeMilliseconds = cursor.GetString(cursor.GetColumnIndexOrThrow(Telephony.TextBasedSmsColumns.Date)).ToProperDouble();
string smsReceivedNumber = cursor.GetString(cursor.GetColumnIndexOrThrow(Telephony.TextBasedSmsColumns.Address));
int smsType = cursor.GetString(cursor.GetColumnIndexOrThrow(Telephony.TextBasedSmsColumns.Type)).ToProperInt();
//you can process this SMS here
if (maxReceivedTimeMilliseconds < smsReceivedTimeMilliseconds) maxReceivedTimeMilliseconds = smsReceivedTimeMilliseconds;
cursor.MoveToNext();
}
//store the last message read date/time stamp to the application property so that the next time, we can read SMS processed after this date and time stamp.
if (totalSMS > 0)
{
Application.Current.Properties["LastSmsReadMilliseconds"] = maxReceivedTimeMilliseconds.ToProperString();
}
}
cursor.Close();
}
}
推荐阅读
- python - 使用 SqlAlchemy 从 Mysql db 获取二进制数据时出现错误
- elasticsearch - 有没有办法在弹性搜索中禁用对文本中数字的模糊搜索?
- c# - 在带锁的对象内使用 Task.Factory.StartNew
- c - 如何在 int safecpy(char **t, char *s) 中使用双指针和 printf?
- c# - C#/Unity3D - 从不同的函数调用时,函数的工作方式不同
- jquery - 如果从输入中获取值(where子句),为什么ajax jquery不起作用
- jenkins - Jenkins 继续运行旧的 Protractor 测试脚本
- algorithm - 基于优先级的实时交错调度问题
- mongodb - 使用 Mongoose 将嵌套对象添加到对象
- java - 尝试访问枚举中名为“name”的字段时,Kotlin 解析不明确