You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android中[Application(UsesCleartextTraffic = true)]的正确配置位置咨询

Fixing the Application(UsesCleartextTraffic = true) Placement Issue in Xamarin Android

Hey there! I see you're stuck with that annoying "The GenerateJavaStub task failed" error after slapping the [Application] attribute directly on your MainActivity—I get why you tried that, but let's fix this the right way.

Why Your Current Setup Breaks

The [Application] attribute in Xamarin Android is only for custom Application classes, not Activity classes. Activities have their own [Activity] attribute, and mixing the two on the same class confuses the build system when it tries to generate the underlying Java stub code—hence that frustrating error.

Correct Approach 1: Create a Custom Application Class

You need a separate class that inherits from Android.App.Application to attach the [Application] attribute to. Here's how to do it step by step:

  1. Add a new class to your project (name it something like MyCustomApp.cs):
using Android.App;
using Android.Runtime;

[Application(UsesCleartextTraffic = true)]
public class MyCustomApp : Application
{
    // Required constructors for Xamarin's binding system
    public MyCustomApp(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
    {
    }

    // Optional: Override lifecycle methods if you need app-level initialization
    public override void OnCreate()
    {
        base.OnCreate();
        // Add any global setup code here if needed
    }
}
  1. Clean up your MainActivity by removing the misplaced [Application] attribute—it should look like this:
using Android.App;
using Android.OS;
using AndroidX.AppCompat.App;

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_main);
        // Rest of your activity logic goes here
    }
}

Correct Approach 2: Edit the AndroidManifest.xml Directly

If you don't want to mess with a custom Application class, you can set the cleartext traffic flag directly in your manifest file. Find the <application> tag and add the attribute there:

<application android:label="@string/app_name" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">
    <!-- Your activity declarations and other app config -->
</application>

Either method will resolve the build error and enable cleartext traffic for your app. The first approach is handy if you ever need to add more app-level configurations or lifecycle logic down the line.

内容的提问来源于stack exchange,提问作者user11674638

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:58:10