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

Android C#后台推送通知实现求助:股价涨1%时触发

Got it, let's walk through building this stock price alert feature step by step for your Xamarin.Android app. I’ll break down each part you need to implement, starting with your existing BroadcastReceiver and adding the necessary background service and notification logic.

First, a quick note: I noticed your receiver class is named MyReciver (typo in "Receiver")—I’ll correct that in the code below to avoid runtime issues.


Step 1: Update Your BroadcastReceiver to Trigger Notifications

We’ll expand your receiver to handle incoming alerts and push system notifications when a stock hits the 1% gain threshold.

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "com.yourpackage.STOCK_PRICE_ALERT" })] // Custom broadcast action
public class MyReceiver : Android.Content.BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        // Pull stock data from the incoming intent
        string stockSymbol = intent.GetStringExtra("StockSymbol");
        double currentPrice = intent.GetDoubleExtra("CurrentPrice", 0);
        double previousPrice = intent.GetDoubleExtra("PreviousPrice", 0);

        // Create a notification channel (required for Android 8.0+)
        CreateNotificationChannel(context);

        // Build notification content
        string alertTitle = $"{stockSymbol} Alert: 1% Gain!";
        string alertText = $"Current: ${currentPrice:F2} | Gain: {CalculateGainPercent(currentPrice, previousPrice):F2}%";

        // Set up intent to open your app when the notification is tapped
        Intent launchIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
        PendingIntent pendingIntent = PendingIntent.GetActivity(
            context,
            0,
            launchIntent,
            PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable
        );

        // Assemble the notification
        Notification alertNotification = new NotificationCompat.Builder(context, "stock_alert_channel")
            .SetSmallIcon(Resource.Drawable.ic_notification) // Replace with your app's notification icon
            .SetContentTitle(alertTitle)
            .SetContentText(alertText)
            .SetPriority(NotificationCompat.PriorityHigh)
            .SetContentIntent(pendingIntent)
            .SetAutoCancel(true)
            .Build();

        // Send the notification
        NotificationManagerCompat.From(context).Notify(1, alertNotification);
    }

    private void CreateNotificationChannel(Context context)
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var channel = new NotificationChannel(
                "stock_alert_channel",
                "Stock Price Alerts",
                NotificationImportance.High
            )
            {
                Description = "Notifications for stock price gains of 1% or more"
            };

            var notificationManager = context.GetSystemService(NotificationManager) as NotificationManager;
            notificationManager?.CreateNotificationChannel(channel);
        }
    }

    private double CalculateGainPercent(double current, double previous)
    {
        return previous == 0 ? 0 : ((current - previous) / previous) * 100;
    }
}

Step 2: Build a Background Service to Monitor Stock Prices

Android restricts background tasks, so we’ll use a Foreground Service (which shows a persistent status bar notification) to reliably check stock prices on a schedule. This service will track previous prices, calculate gains, and trigger the broadcast when thresholds are met.

[Service(ForegroundServiceType = ForegroundService.TypeDataSync)]
public class StockMonitorService : Service
{
    private Timer _priceCheckTimer;
    private const int CheckIntervalMinutes = 5; // Adjust how often to check prices
    private readonly Dictionary<string, double> _lastRecordedPrices = new();

    public override IBinder OnBind(Intent intent) => null;

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        // Start the service in foreground mode (required for long-running background tasks)
        StartForeground(1001, CreateServiceNotification());

        // Initialize timer to check prices on schedule
        _priceCheckTimer = new Timer(CheckStockPrices, null, TimeSpan.Zero, TimeSpan.FromMinutes(CheckIntervalMinutes));

        return StartCommandResult.Sticky; // Restart service if it's killed
    }

    private void CheckStockPrices(object state)
    {
        // Replace this with your actual stock price API call
        // Example: Fetch real prices using a financial API like Alpha Vantage or Yahoo Finance
        var currentStockPrices = new Dictionary<string, double>
        {
            { "AAPL", 182.45 },
            { "GOOGL", 143.70 }
        };

        foreach (var (symbol, currentPrice) in currentStockPrices)
        {
            if (_lastRecordedPrices.TryGetValue(symbol, out double previousPrice))
            {
                double gainPercent = CalculateGainPercent(currentPrice, previousPrice);

                // Trigger alert if gain is 1% or more
                if (gainPercent >= 1.0)
                {
                    SendAlertBroadcast(symbol, currentPrice, previousPrice);
                }
            }

            // Update stored price for next check
            _lastRecordedPrices[symbol] = currentPrice;
        }
    }

    private void SendAlertBroadcast(string symbol, double currentPrice, double previousPrice)
    {
        var alertIntent = new Intent("com.yourpackage.STOCK_PRICE_ALERT");
        alertIntent.PutExtra("StockSymbol", symbol);
        alertIntent.PutExtra("CurrentPrice", currentPrice);
        alertIntent.PutExtra("PreviousPrice", previousPrice);

        SendBroadcast(alertIntent);
    }

    private Notification CreateServiceNotification()
    {
        CreateServiceNotificationChannel(this);

        return new NotificationCompat.Builder(this, "stock_service_channel")
            .SetSmallIcon(Resource.Drawable.ic_service) // Replace with a service icon
            .SetContentTitle("Stock Monitor Running")
            .SetContentText("Tracking your stocks in the background")
            .SetPriority(NotificationCompat.PriorityLow)
            .Build();
    }

    private void CreateServiceNotificationChannel(Context context)
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var channel = new NotificationChannel(
                "stock_service_channel",
                "Stock Monitoring Service",
                NotificationImportance.Low
            )
            {
                Description = "Foreground service for tracking stock prices"
            };

            var notificationManager = context.GetSystemService(NotificationManager) as NotificationManager;
            notificationManager?.CreateNotificationChannel(channel);
        }
    }

    public override void OnDestroy()
    {
        // Clean up timer when service stops
        _priceCheckTimer?.Dispose();
        base.OnDestroy();
    }

    private double CalculateGainPercent(double current, double previous)
    {
        return previous == 0 ? 0 : ((current - previous) / previous) * 100;
    }
}

Step 3: Add Required Permissions to AndroidManifest.xml

Open your project’s AndroidManifest.xml and add these permissions to enable notifications, foreground services, and network access (for fetching stock prices):

<!-- Notification permission (Android 13+) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Foreground service permission -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- Internet access for API calls -->
<uses-permission android:name="android.permission.INTERNET" />

If Xamarin doesn’t auto-register your service/receiver via attributes, add these entries inside the <application> tag:

<receiver android:name=".MyReceiver" />
<service android:name=".StockMonitorService" android:foregroundServiceType="dataSync" />

Step 4: Start the Service from Your App

Launch the monitoring service when your app opens (e.g., in your main Activity’s OnCreate method):

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.activity_main);

    // Request notification permission for Android 13+
    if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
    {
        RequestPermissions(new[] { Manifest.Permission.PostNotifications }, 100);
    }

    // Start the stock monitoring service
    var serviceIntent = new Intent(this, typeof(StockMonitorService));
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        StartForegroundService(serviceIntent);
    }
    else
    {
        StartService(serviceIntent);
    }
}

Key Notes to Customize
  • Stock Price API: Replace the hardcoded currentStockPrices with actual API calls. Use async/await for network requests (avoid blocking the timer thread).
  • Notification Icons: Add transparent vector icons named ic_notification and ic_service to your Resource.Drawable folder.
  • Check Interval: Adjust CheckIntervalMinutes to match how frequently you want to poll for price updates.
  • Background Limits: Android 12+ has strict background rules—using a foreground service is the most reliable way to keep the monitoring task running.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:44:47