Call service method from notification with BroadcastReceiver in Xamarin Android

妖精的绣舞 提交于 2019-12-07 06:08:25

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!