简体   繁体   中英

Call service method from notification with BroadcastReceiver in Xamarin Android

I start a service and create new thread (downloading a large file). At the same time I display a notification with action (pause button). When I press this button "WSTRZYMAJ" I want call PauseDownload() method from my service. How can I do this? I have read about BroadcastReceiver, create this class but how to call method from service from BroadcastReceiver class?

Screen from notification: 通知

Fragment of my service:

class DownloadsService : Service
{
    DownloadsBroadcastReceiver receiver;
    Notification.Builder notificationBuilder;
    DownloadsData downloadsData;
    int uniqueNumber = 1000;
    bool isStarted;

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        RegisterReceiver(receiver, new IntentFilter("com.xamarin.example.TEST"));
        downloadsData = JsonConvert.DeserializeObject<DownloadsData>(intent.GetStringExtra("downloadsData"));
        if (isStarted)
            Log.Info("DAMIAN", "Error start service");
        else
        {
            Log.Info("DAMIAN", "Start service");
            DispatchNotificationThatServiceIsRunning(downloadsData.Name, "Started");
            new Thread(new ThreadStart(() =>
            {
                MakeDownload();
            })).Start();
            isStarted = true;
        }
        return StartCommandResult.NotSticky;
    }

    private void DispatchNotificationThatServiceIsRunning(string title, string content)
    {
        Intent stopIntent = new Intent(this, typeof(DownloadsBroadcastReceiver));
        stopIntent.PutExtra("action", "actionName");
        PendingIntent stopPi = PendingIntent.GetBroadcast(this, 4, stopIntent, PendingIntentFlags.UpdateCurrent);
        Intent intent = new Intent(this, typeof(MainActivity));
        TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
        stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
        stackBuilder.AddNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
        Notification.Action pauseAction = new Notification.Action.Builder(Resource.Drawable.Pause, "WSTRZYMAJ", stopPi).Build();
        notificationBuilder = new Notification.Builder(this)
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentIntent(resultPendingIntent)
            .SetContentTitle(title)
            .SetContentText(content)
            .AddAction(pauseAction);
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(uniqueNumber, notificationBuilder.Build());
    }

    private void UpdateNotification(string content)
    {
        notificationBuilder.SetContentText(content);
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(uniqueNumber, notificationBuilder.Build());
    }

    private void MakeDownload()
    {
    //downloading file
    }

    private void PauseDownload()
    {
    //pause downloading
    }
}

And full code BroadcastReceiver class:

[BroadcastReceiver(Enabled = true, Exported = false)]
[IntentFilter(new[] { "com.xamarin.example.TEST" })]
class DownloadsBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        String action = intent.GetStringExtra("action");
        if (action.Equals("actionName"))
            Log.Info("DAMIAN", "BROADCAST"); //it works, ie. I have text "BROADCAST" in log
    }
}

how to call method from service from BroadcastReceiver class?

When you receive message in DownloadsBroadcastReceiver , you could start your DownloadsService again. When you did this, since your DownloadsService has been created, it will call OnStartCommand() method, so you will receive message in this method, you could call PauseDownload() in OnStartCommand() method.

Usage like this :

[BroadcastReceiver(Enabled = true, Exported = false)]
[IntentFilter(new[] { "com.xamarin.example.TEST" })]
public class DownloadsBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        String action = intent.GetStringExtra("action");
        if ("actionName".Equals(action))
        {
            Intent intent2 = new Intent(Application.Context, typeof(DownloadsService));
            intent2.PutExtra(action, "actionName");

            Application.Context.StartService(intent2);
        }
    }
}

In your DownloadsService class :

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
     String action = intent.GetStringExtra("action");
     if ("actionName".Equals(action))
     {
        PauseDownload();
     }

     ...
     return StartCommandResult.NotSticky;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM