1
使用xamarin形式我試圖讀取傳入的消息並使用廣播接收器類顯示Toast消息。Xamarin形式android使用廣播接收器接收傳入的文本消息
以下是我的manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
<uses-sdk android:minSdkVersion="22" android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<application android:label="DemoApp" android:debuggable="true">
</application>
</manifest>
接收機類
[BroadcastReceiver(Enabled = true, Exported = true,Label = "SMS Receiver")]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED"}, Priority = Int32.MaxValue)]
public class SmsReceiver : Android.Content.BroadcastReceiver
{
public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsReceiver()
{
}
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action == INTENT_ACTION)
{
if (ContextCompat.CheckSelfPermission(context,
"android.permission.READ_SMS") != Permission.Denied)
{
Bundle bundle = intent.Extras;
if (bundle != null)
{
Java.Lang.Object[] pdus = (Java.Lang.Object[])bundle.Get("pdus");
if (pdus.Length == 0)
{
return;
}
SmsMessage[] msgs;
msgs = new SmsMessage[pdus.Length];
for (int i = 0; i < msgs.Length; i++)
{
msgs[i] = SmsMessage.CreateFromPdu((byte[])pdus[i], "3gpp");
Log.Info("SmsReceiver", "SMS Received from: " + msgs[i].OriginatingAddress);
Log.Info("SmsReceiver", "SMS Data: " + msgs[i].MessageBody.ToString());
}
Toast.MakeText(context.ApplicationContext, "SUCCESS",
ToastLength.Long).Show();
Log.Info("SmsReceiver", "SMS Received");
}
}
}
}
}
但上面的代碼沒有顯示在日誌貓也不敬酒文本信息的日誌信息。 任何人都可以幫我出來