无法将源类型转换为目标类型(JNIEnv.GetArray<Java.Lang.Object>(pudis.Handle);)

4

我正在尝试在我的应用程序中接收短信。

我在项目中拥有一个BroadcastReceiver类,但是我遇到了运行时错误:

System.InvalidCastException:无法从源类型强制转换为目标类型。 在 at(包装castclass) object.__castclass_with_cache(object,intptr,intptr)at at Android.Runtime.JNIEnv.CopyArray (intptr,Java.Lang.Object [])&lt;0x002a3>在 at Android.Runtime.JNIEnv.GetArray (intptr)&lt;0x0021f> <br /> 在Messages.SMSBroadcastReceiver.OnReceive (Android.Content.Context,Android.Content.Intent)[0x0005f]中 c:\ Users \ Jase \ Documents \ Projects \ Messages \ Messages \ SMSBroadcastReceiver.cs:36 在 Android.Content.BroadcastReceiver.n_OnReceive_Landroid_content_Context_Landroid_content_Intent_ (intptr,intptr,intptr,intptr)[0x00019]中 /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(wrapper dynamic-method) object.145a0c82-0de6-4c2c-90a0-3654436a06c3 (intptr,intptr,intptr,intptr)

这是我正在使用的代码:

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();
        }
    }
}

我一直在努力想出一个解决方案,已经搜索了几个小时,但是现有的解决此错误的方法都没有起作用。我不明白。请问有人能帮忙解释一下吗?


我更新了这个问题:

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

我想指出的是,我尝试了许多方法来解决这个问题。现在我已经浏览了谷歌搜索结果的第60页,试图找到一些东西。问题在于,我在网上找到的所有解决这个确切错误的解决方案都不起作用,因为它们基本上只是同一陈述的微小变化,只是写法略有不同,但会产生相同的结果异常。

我还尝试了以下方法:

//                    var castedPdus = JNIEnv.GetObjectArrayElement(pdus.Handle, 0);
//                    Object castedPdus = (Object)bundle.Get("pdus");
//                    var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);

没有任何运气。

根据我使用的语句不同,异常会有所不同,从“无法将源类型转换为目标类型”到“无法将object[]转换为object”。好吧,显而易见。但问题不在于我“做错了”,而是我们被告知要“做错”。我找不到在线上其他接收Xamarin短信的方法。每个在线示例似乎都基于这个代码片段 - 或多或少有一些小的改动。现在我不知道该怎么办了。甚至看起来没有一丝希望。


1
经过大量的研究,我发现这实际上是一个错误,而不是我们做错了什么。似乎没有任何替代方法可以使用我正在使用的方法,也没有其他资源表明可以以不同的方式完成此操作。因此,我的解决方案是使用Android Studio在Java中重写项目。我已经编写了一个可工作的SMSReceiver。就目前而言,我认为Xamarin并不是非常可靠的。他们还需要做很多工作,才能让我信赖它来处理任何严肃的事情。 - jay_t55
3个回答

1

到现在为止,您可能已经使用Java实现了您的应用程序,但是这里是我在Android 5.0上读取PDU的解决方案。

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);

顺便提一下,这似乎是一个与 Xamarin 相关的 bug。请查看 Bugzilla Issue 26674


1

既然你说你要使用Java和Android Studio,但没有留下答案,我在这里为你和其他可能正在寻找解决方案的人留下一个答案。

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();
            }
        }
    }
}

请务必在AndroidManifest.xml文件中添加所需的权限和意图过滤器。

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>

0

这里还有另一种选择:

[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));
        }

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接