Android: 使用意图引发的Java.Lang.RuntimeException

huangapple go评论77阅读模式
英文:

Android : Java.Lang.RuntimeException with intent

问题

我正在Android上开发两个应用程序:应用程序A,当按下按钮时应该打开应用程序B,应用程序B应该返回一个值给应用程序A,例如"OK"。为了实现这个目标,应用程序A发送一个带有动作"com.intent.test"的意图,但当它接收到意图时,应用程序B会崩溃,并显示以下错误消息:

Java.Lang.RuntimeException: '无法实例化活动ComponentInfo{com.example.newdemo/com.example.newdemo.MainActivity}:java.lang.ClassNotFoundException:在路径上找不到类"com.example.demointent.MainActivity":DexPathList[[zip文件"/data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/lib/arm64,/data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/base.apk!/lib/arm64-v8a,/system/lib64,/system/product/lib64]]'

AndroidManifest.xml应用程序B:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.example.demointent" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="33" />
    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:label="@string/app_name" android:exported="true" android:enabled="true">
            <intent-filter>
                <action android:name="com.intent.test" />
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

应用程序B的MainActivity:

namespace NewDemo
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                base.OnCreate(savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                SetContentView(Resource.Layout.activity_main);

                Intent receivedIntent = Intent;
                if (receivedIntent == null) return;

                var dataReceived = receivedIntent.GetStringExtra("key");
                var action = receivedIntent.Action;

                var intent = new Intent();
                switch (action)
                {
                    case "com.intent.test":
                        intent.PutExtra("result", "OK");
                        break;
                }

                SetResult(Result.Ok, intent);
                Toast.MakeText(this, "My app is started. Data: " + dataReceived, ToastLength.Short)?.Show();
                Finish();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "error: " + ex.Message, ToastLength.Short)?.Show();
            }

        }
    }
}

应用程序A的MainActivity:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    SetContentView(Resource.Layout.activity_main);
    var btnstartWithAction = FindViewById<TextView>(Resource.Id.btnstartWithAction);
    if (btnstartWithAction != null)
    {
        btnstartWithAction.Click += (sender, e) =>
        {
            var intent = new Intent();
            var action = "com.intent.test";
            intent.SetAction(action);
            intent.PutExtra("key", "keytest");

            StartActivityForResult(Intent.CreateChooser(intent, "App"), 3);
        };
    }
}

当我使用带有动作的意图时出现此错误。当应用程序A使用包名称调用应用程序B时,我没有问题。像这样:

Intent launchIntent = ApplicationContext.PackageManager.GetLaunchIntentForPackage("com.example.newdemo");
launchIntent?.SetFlags(0);
launchIntent?.SetAction("com.intent.test");
launchIntent?.PutExtra("key", "12345");
StartActivityForResult(Intent.CreateChooser(launchIntent, ""), 12);

我已经多次清理和构建了我的项目。我在使用Xamarin和Visual Studio 2022进行C#编码。有人知道发生了什么吗?
谢谢。

英文:

I am developing two apps on Android: app A which when a button is pressed should open app B which should return a value to app A, like "OK". To do this, app A sends an intent with the action "com.intent.test", but when it receives the intent, app B crashes with the following error message:

Java.Lang.RuntimeException: 'Unable to instantiate activity ComponentInfo{com.example.newdemo/com.example.newdemo.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.demointent.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/lib/arm64, /data/app/com.example.demointent-SsbNhZc7TrVyMjaIbZDfVw==/base.apk!/lib/arm64-v8a, /system/lib64, /system/product/lib64]]'

AndroidManifest.xml app B :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:versionCode=&quot;1&quot; android:versionName=&quot;1.0&quot; package=&quot;com.example.demointent&quot; android:installLocation=&quot;auto&quot;&gt;
    &lt;uses-sdk android:minSdkVersion=&quot;21&quot; android:targetSdkVersion=&quot;33&quot; /&gt;
    &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:theme=&quot;@style/AppTheme&quot;&gt;
        &lt;activity android:name=&quot;.MainActivity&quot; android:label=&quot;@string/app_name&quot; android:exported=&quot;true&quot; android:enabled=&quot;true&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;com.intent.test&quot; /&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
                &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
    &lt;/application&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
&lt;/manifest&gt;

MainActivity app B:

namespace NewDemo
{
    [Activity(Label = &quot;@string/app_name&quot;, Theme = &quot;@style/AppTheme&quot;, MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                base.OnCreate(savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                SetContentView(Resource.Layout.activity_main);

                Intent receivedIntent = Intent;
                if (receivedIntent == null) return;

                var dataReceived = receivedIntent.GetStringExtra(&quot;key&quot;);
                var action = receivedIntent.Action;

                var intent = new Intent();
                switch (action)
                {
                    case &quot;com.intent.test&quot;:
                        intent.PutExtra(&quot;result&quot;, &quot;OK&quot;);
                        break;
                }

                SetResult(Result.Ok, intent);
                Toast.MakeText(this, &quot;My app is started. Data: &quot; + dataReceived, ToastLength.Short)?.Show();
                Finish();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, &quot;error: &quot; + ex.Message, ToastLength.Short)?.Show();
            }

        }
    }
}

MainActivity app A:

      protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            var btnstartWithAction = FindViewById&lt;TextView&gt;(Resource.Id.btnstartWithAction);
            if (btnstartWithAction != null)
            {
                btnstartWithAction.Click += (sender, e) =&gt;
                {
                    var intent = new Intent();
                    var action = &quot;com.intent.test&quot;;
                    intent.SetAction(action);
                    intent.PutExtra(&quot;key&quot;, &quot;keytest&quot;);

                    StartActivityForResult(Intent.CreateChooser(intent, &quot;App&quot;), 3);
                };
            }
        }

This error appears when I use the intent with action. When app A call App B with the package name, I don't have a problem. Like this :

                   Intent launchIntent = ApplicationContext.PackageManager.GetLaunchIntentForPackage(&quot;com.example.newdemo&quot;);
                    launchIntent?.SetFlags(0);
                    launchIntent?.SetAction(&quot;com.intent.test&quot;);
                    launchIntent?.PutExtra(&quot;key&quot;, &quot;12345&quot;);
                    StartActivityForResult(Intent.CreateChooser(launchIntent, &quot;&quot;), 12);

I have already cleaned and built my project several times. I'm coding in c# with Xamarin and visual studio 2022. does anyone have any idea what is going on?
Thanks.

答案1

得分: 0

Java.Lang.RuntimeException: '无法实例化活动ComponentInfo{com.example.newdemo/com.example.newdemo.MainActivity}:java.lang.ClassNotFoundException: 找不到类"com.example.demointent.MainActivity"

在Xamarin.Android中,默认情况下会使用基于MD5的类名生成Java包装器,以避免Java类名冲突,例如:

md579731053346ff64fcf21847b09163ce1.MainActivity

您在清单中硬编码了"activity android:name=".MainActivity"",但生成的类默认情况下将是基于MD5的。

您应该避免混合使用声明性属性和手动编写AndroidManifest.xml。

"[Activity (Label = "MyApp", MainLauncher = true, Icon = "@mipmap/ic_launcher")]"正在生成实际使用的(生成的)AndroidManifest.xml中的一段代码,看起来像:






而您的代码将在其他位置。您可以在输出文件夹.\obj\Debug\android中找到生成的AndroidManifest.xml。

因此,尝试从清单文件中删除手动编辑,并通过属性添加您需要的内容。

例如:

[Activity(Label = "SearchBarDemos", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, Exported = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[
IntentFilter
(
new[] { Android.Content.Intent.ActionView },
Categories = new[]
{
Android.Content.Intent.CategoryDefault,
Android.Content.Intent.CategoryBrowsable
},
DataSchemes = new[] { "myapp" }
)
]
public class MainActivity: Activity
{

}

英文:

> Java.Lang.RuntimeException: 'Unable to instantiate activity
> ComponentInfo{com.example.newdemo/com.example.newdemo.MainActivity}:
> java.lang.ClassNotFoundException: Didn't find class
> "com.example.demointent.MainActivity"

On Xamarin.Android, by default, generates the Java wrappers using MD5-based class names to avoid Java class name clashing, such as:

 md579731053346ff64fcf21847b09163ce1.MainActivity 

You have hard-coded a activity android:name=&quot;.MainActivity&quot; in your manifest but the generated class will be MD5-based by default.

You should avoid to mix up declarative attributes and manually writing the AndroidManifest.xml.

[Activity (Label = &quot;MyApp&quot;, MainLauncher = true, Icon = &quot;@mipmap/ic_launcher&quot;)] is generating a piece of code in the actual used (generated) AndroidManifest.xml that looks like:

  &lt;activity android:icon=&quot;@drawable/icon&quot; android:label=&quot;AndroidApp1&quot; android:name=&quot;md5c178831cd46fc53bebc42cf953f78ced.MainActivity&quot;&gt;
  &lt;intent-filter&gt;
    &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
    &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
  &lt;/intent-filter&gt;
&lt;/activity&gt;

and your code will be somewhere else. You can find the generated AndroidManifest.xml in the output folder .\obj\Debug\android.

So,try to remove the manual edits from your manifest file and add your stuff via attributes if you need.

For example:

[Activity(Label = &quot;SearchBarDemos&quot;, Icon = &quot;@mipmap/icon&quot;, Theme = &quot;@style/MainTheme&quot;, MainLauncher = true,Exported =true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] 
    [
    IntentFilter
    (
        new[] { Android.Content.Intent.ActionView },
        Categories = new[]
            {
                Android.Content.Intent.CategoryDefault,
                Android.Content.Intent.CategoryBrowsable
            },
        DataSchemes = new[] { &quot;myapp&quot; }
    )
]
    public class MainActivity:Activity
 {

 }

huangapple
  • 本文由 发表于 2023年7月12日 22:27:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定