Xamarin Android中[Application(UsesCleartextTraffic = true)]的正确配置位置咨询
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:
- 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 } }
- Clean up your
MainActivityby 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

