Xamarin Forms Android后台上传服务实现方案咨询
Hey there! I’ve actually tackled similar background upload scenarios in Xamarin Forms for Android, so let me break down your options clearly.
Using android-upload-service in Xamarin Forms
Good news—there’s an official Xamarin binding for this library available as a NuGet package. You don’t have to roll your own binding from scratch. Here’s a quick implementation outline:
Install the NuGet package
In your Android project, installXamarin.Android.UploadService(stick to the latest stable version for reliability).Initialize the library in Android project
Open yourMainApplication.csand add initialization code in theOnCreatemethod:protected override void OnCreate() { base.OnCreate(); // Initialize the upload service UploadService.Initialize(this, true); // Set up a notification channel for Android O+ (required for foreground notifications) UploadService.CreateNotificationChannel(this, "UploadChannel", "Uploads", "Background upload notifications", NotificationImportance.Default); }Create a dependency service for cross-platform access
In your shared Xamarin Forms project, define an interface to abstract upload logic:public interface IFileUploader { void UploadFile(string filePath, string uploadUrl); }Then implement this interface in your Android project:
[assembly: Dependency(typeof(AndroidFileUploader))] namespace YourApp.Droid { public class AndroidFileUploader : IFileUploader { public void UploadFile(string filePath, string uploadUrl) { var uploadRequest = new MultipartUploadRequest( Guid.NewGuid().ToString(), uploadUrl ) .AddFileToUpload(filePath, "file") // "file" matches your API's form field name .SetNotificationConfig(new UploadNotificationConfig() { NotificationChannelId = "UploadChannel", Title = "Uploading File", ProgressMessage = "In progress...", CompletedMessage = "Upload finished!", ErrorMessage = "Upload failed" }); UploadService.StartUpload(uploadRequest); } } }Trigger uploads from shared code
In your Xamarin Forms pages or view models, use the dependency service to kick off uploads:var uploader = DependencyService.Get<IFileUploader>(); uploader.UploadFile(localFilePath, "https://your-api-endpoint.com/upload");
Alternative: WorkManager + OkHttp
If you prefer a more native Android approach without third-party libraries, using WorkManager (part of Jetpack) paired with OkHttp is a solid, reliable option. WorkManager handles background task scheduling, retries, and adapts to Android’s strict background restrictions.
Add required NuGet packages
InstallXamarin.AndroidX.Work.RuntimeandSquare.OkHttp3in your Android project.Create a Worker class for upload logic
public class FileUploadWorker : Worker { public FileUploadWorker(Context context, WorkerParameters parameters) : base(context, parameters) { } public override Result DoWork() { var filePath = InputData.GetString("filePath"); var uploadUrl = InputData.GetString("uploadUrl"); try { var file = new File(filePath); var client = new OkHttpClient(); var requestBody = new MultipartBody.Builder() .SetType(MultipartBody.Form) .AddFormDataPart("file", file.Name, RequestBody.Create(file, MediaType.Parse("application/octet-stream"))) .Build(); var request = new Request.Builder() .Url(uploadUrl) .Post(requestBody) .Build(); var response = client.NewCall(request).Execute(); if (!response.IsSuccessful) throw new IOException($"Upload failed: {response.Message}"); return Result.InvokeSuccess(); } catch (Exception ex) { // Return retry to let WorkManager handle retries (adjust policy when enqueuing) return Result.InvokeRetry(); } } }Schedule the worker via dependency service
Implement the sameIFileUploaderinterface in Android using WorkManager:[assembly: Dependency(typeof(AndroidWorkManagerUploader))] namespace YourApp.Droid { public class AndroidWorkManagerUploader : IFileUploader { public void UploadFile(string filePath, string uploadUrl) { var inputData = new Data.Builder() .PutString("filePath", filePath) .PutString("uploadUrl", uploadUrl) .Build(); var uploadWorkRequest = OneTimeWorkRequest.Builder<FileUploadWorker>() .SetInputData(inputData) .SetConstraints(new Constraints.Builder() .SetRequiredNetworkType(NetworkType.Connected) // Only run when online .Build()) .Build(); WorkManager.GetInstance(Android.App.Application.Context).Enqueue(uploadWorkRequest); } } }
Key Tips for Android Background Uploads
- Permissions: For Android 13+, you need the
POST_NOTIFICATIONSpermission to show upload progress alerts. Also, use app-specific storage instead of external storage where possible to avoid runtime permission prompts, and ensure you have theINTERNETpermission enabled. - Background Stability: Android 8.0+ limits background services, so using libraries like android-upload-service (which uses foreground services with notifications) or WorkManager is non-negotiable to prevent task cancellation.
- Progress Tracking: Both options support progress updates—for android-upload-service, register a broadcast receiver; for WorkManager, observe work status from your shared code to update the UI.
内容的提问来源于stack exchange,提问作者markpirvine

