广播接收器不通过 Xamarin 中的 OnReceive 方法显示 Toast Android

Broadcast Receiver not displaying Toast via OnReceive method in Xamarin Android

我正在尝试在我的项目中实现广播接收器 class,我有一个扩展 class BroadcastReceiver 的接收器,我打算检查是否通过单击按钮接收到广播,OnReceive方法内部有一个 Toast 代码,如果广播发送成功,它应该显示消息 Intent Detected。我的代码看起来像这样...

 class FlashActivity : AppCompatActivity
    {
           protected override void OnCreate(Bundle savedInstanceState)
           {
         //Button definition
            Button button1 = this.FindViewById<Button>(Resource.Id.button1);
        //Clicking on this button should send the Broadcast message
            button1.Click += broadCastIntent;
           }
      //Method to send broadcast message on button click
       private void broadCastIntent(object sender,EventArgs e)
        {
            Intent intent = new Intent();
            intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
            SendBroadcast(intent);
        }
       //BroadCast Receiver class Implementation

       [BroadcastReceiver(Name="com.Java_Tutorial.CUSTOM_INTENT")]
        public class MyReceiver: BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
           //Acknowledge message was received via a Toast
                Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
            }
        }
    }

我的 Manifest.xml 文件的接收器代码部分如下所示

<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
        <receiver android:name="MyReceiver">
            <intent-filter>
                <action android:name="com.Java_Tutorial.CUSTOM_INTENT"></action>
            </intent-filter>
        </receiver>
    </application>

当我点击按钮时,没有显示吐司,请帮助...

您需要添加 IntentFilter 属性

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "com.Java_Tutorial.CUSTOM_INTENT" })]
public class MyReceiver: BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
     {
         //Acknowledge message was received via a Toast
         Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
     }
}

When i click the button, No Toast is displayed

您没有在 Activity 中注册 BroadcastReceiver

请按以下代码注册。

  [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        MyReceiver receiver;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            Button button1 = this.FindViewById<Button>(Resource.Id.button1);

             receiver = new  MyReceiver();
            //Clicking on this button should send the Broadcast message
            button1.Click += broadCastIntent; ;
          
        }

      

        private void broadCastIntent(object sender, System.EventArgs e)
        {
            Intent intent = new Intent();
            intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
            SendBroadcast(intent);

           
        }
        //BroadCast Receiver class Implementation
        protected override void OnResume()
        {
            base.OnResume();
            RegisterReceiver(receiver, new IntentFilter("com.Java_Tutorial.CUSTOM_INTENT"));
            // Code omitted for clarity
        }

        protected override void OnPause()
        {
            UnregisterReceiver(receiver);
            // Code omitted for clarity
            base.OnPause();
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    
    [BroadcastReceiver(Name = "com.Java_Tutorial.CUSTOM_INTENT")]
    public class MyReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            //Acknowledge message was received via a Toast
            Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
        }
    }
}

这是运行 GIF。

这是一篇关于广播的有用文章。你可以参考一下。

https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/broadcast-receivers#context-registering-a-broadcast-receiver

更新

tried to find a post where you detect if flashlight is already on via a broadcast and then toggle switch accordingly in my app

Android OS不提供手电筒系统广播。但是我们可以检查手电筒的status.If手电筒的状态是打开的,我们可以发送一个广播,然后我们的broadcastReceiver来获取它。

// note: camera come from:  private Android.Hardware.Camera camera=Android.Hardware.Camera.Open();

 if (camera.GetParameters().FlashMode.Equals(Android.Hardware.Camera.Parameters.FlashModeOff))
            {
                switchOn = false;
            }
            else if (camera.GetParameters().FlashMode.Equals(Android.Hardware.Camera.Parameters.FlashModeTorch))
            {
                switchOn = true;
                Intent intent = new Intent();
                intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
                SendBroadcast(intent);
            }