Reputation: 11662
I am trying to receive SMS in my app.
I've got a BroadcastReceiver class in my project and I am receiving a runtime error:
System.InvalidCastException: Cannot cast from source type to destination type. at at (wrapper castclass) object._castclass_with_cache (object,intptr,intptr) <IL 0x0002c, 0x00080> at at Android.Runtime.JNIEnv.CopyArray<Java.Lang.Object> (intptr,Java.Lang.Object[]) <0x002a3> at at Android.Runtime.JNIEnv.GetArray<Java.Lang.Object> (intptr) <0x0021f>
at Messages.SMSBroadcastReceiver.OnReceive (Android.Content.Context,Android.Content.Intent) [0x0005f] in c:\Users\Jase\Documents\Projects\Messages\Messages\SMSBroadcastReceiver.cs:36 at Android.Content.BroadcastReceiver.n_OnReceive_Landroid_content_Context_Landroid_content_Intent (intptr,intptr,intptr,intptr) [0x00019] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.20-series/ba9bbbdd/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Android.Content.BroadcastReceiver.cs:334 at at (wrapper dynamic-method) object.145a0c82-0de6-4c2c-90a0-3654436a06c3 (intptr,intptr,intptr,intptr) <IL 0x0001d, 0x0004b>
Here's the code that I'm using:
using System;
using System.Text;
using Android.App;
using Android.OS;
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Widget;
using Android.Telephony;
using Environment = System.Environment;
namespace Messages
{
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SMSBroadcastReceiver : BroadcastReceiver
{
private const string Tag = "SMSBroadcastReceiver";
private const string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
Log.Info(Tag, "Intent: " + intent.Action);
if (intent.Action != IntentAction)
return;
var bundle = intent.Extras;
if (bundle == null)
return;
var pdus = bundle.Get("pdus");
// ********** This is the error line at runtime ****************
var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);
var messages = new SmsMessage[castedPdus.Length];
var stringBuilder = new StringBuilder();
for (int i = 0; i < messages.Length; i++)
{
var bytes = new byte[JNIEnv.GetArrayLength(castedPdus[i].Handle)];
JNIEnv.CopyArray(castedPdus[i].Handle, bytes);
messages[i] = SmsMessage.CreateFromPdu(bytes);
stringBuilder.Append(String.Format("SMS from: {0}{1}Body: {2}{1}", messages[i].OriginatingAddress,
Environment.NewLine, messages[i].MessageBody));
}
Toast.MakeText(context, stringBuilder.ToString(), ToastLength.Long).Show();
}
}
}
I've been trying to come up with a solution and have been searching but none of the existing solutions to this error have worked. What can I try next?
I'm updating this question with:
Bundle not null: Bundle[mParcelledData.dataSize=256]
PDUS: [[B@5s294833
PDUS Handle: 2065454
Cannot cast from source type to destination type. at (wrapper castclass) object:__castclass_with_cache (object,intptr,intptr)
at Android.Runtime.JNIEnv.CopyArray[Object] (IntPtr src, Java.Lang.Object[] dest) [0x00078] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.20-series/ba9bbbdd/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.cs:946
at Android.Runtime.JNIEnv.GetArray[Object] (IntPtr array_ptr) [0x00053] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.20-series/ba9bbbdd/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.cs:1211
at Java.Lang.Object.ToArray[Object] () [0x00000] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.20-series/ba9bbbdd/source/monodroid/src/Mono.Android/src/Java.Lang/Object.cs:338
at Java.Lang.Object.op_Explicit (Java.Lang.Object value) [0x00008] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.20-series/ba9bbbdd/source/monodroid/src/Mono.Android/src/Java.Lang/Object.cs:499
at Messages.SMSBroadcastReceiver.OnReceive (Android.Content.Context context, Android.Content.Intent intent) [0x000ba] in c:\Users\Jase\Documents\Projects\Messages\Messages\SMSBroadcastReceiver.cs:52
I'd also like to note that I have tried many things to resolve this issue. I am now (really) on page 60 of Google's search results, trying to find something. Problem is, none of the solutions I've found online for this exact same error actually work because they're basically just tiny little variatings of the same statement, just written in a slightly different way but does the same thing which produces the same exception.
I have also tried the following:
// var castedPdus = JNIEnv.GetObjectArrayElement(pdus.Handle, 0);
// Object castedPdus = (Object)bundle.Get("pdus");
// var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);
without any luck.
Depending on which statement I use, exceptions vary from "Cannot cast from source type to destination type", to "Cannot convert object[] to object". Well, duh. But the issue is not that I'm "doing it wrong", it's that we're told to do it "wrong". There is no other way of receiving an SMS in Xamarin that I can find online. Every single example online seems to be based off of this one code snippet - give or take a few minor alterations.
Upvotes: 4
Views: 1271
Reputation: 1297
Here is another alternative:
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SMSBroadcastReceiver : BroadcastReceiver, ISMSReceiver
{
private const string Tag = "SMSBroadcastReceiver";
private const string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
Log.Info(Tag, "Intent received: " + intent.Action);
if (intent.Action != IntentAction) return;
SmsMessage[] messages=Telephony.Sms.Intents.GetMessagesFromIntent (intent);
var sb = new StringBuilder();
for (var i = 0; i < messages.Length; i++)
{
sb.Append(string.Format("SMS From: {0}{1}Body: {2}{1}", messages[i].OriginatingAddress,
Environment.NewLine,messages[i].MessageBody));
}
}
}
Upvotes: 0
Reputation: 8013
By now you've probably already implemented your app in Java, but here's my solution to reading out the pdu's on Android 5.0.
Java.Lang.Object rawPdus = intent.Extras.Get("pdus");
int length = JNIEnv.GetArrayLength(rawPdus.Handle);
if (length < 1)
return;
var pdus = JNIEnv.GetArrayItem<byte[]>(rawPdus.Handle, 0);
var msg = SmsMessage.CreateFromPdu(pdus);
It appears to be a Xamarin related bug by the way. Check Bugzilla Issue 26674.
Upvotes: 1
Reputation: 806
Since you said you're going to use Java with Android Studio, but did not leave an answer, I'm leaving one here for you and anybody else who may be looking for a solution.
SmsReceiver.java:
package com.your.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
Log.d("SNDR", sender);
String message = sb.toString();
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
// prevent any other broadcast receivers from receiving broadcast
abortBroadcast();
}
}
}
}
Be sure to add the required permission and intent-filter to your AndroidManifest.xml file.
AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.your.app.SmsReceiver" android:enabled="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
Upvotes: 1