Xamarin BroadcastReceiver OnReceiveGetResultExtras为空

m0rkklqb  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

我正在使用Visual Studio 2022和Xamarin做一个Android应用程序,发现OnReceive方法什么都没有接收。我已经遵循了我发现的一些示例,但它不起作用。我使用的代码如下:

public class MainActivity : AppCompatActivity
{

  protected override void OnCreate(Bundle savedInstanceState)
  {
    Intent intent = new Intent(RecognizerIntent.ActionGetLanguageDetails);
    SendOrderedBroadcast(intent, null, new LanguageDetailsChecker(), null, Result.Ok, null, null);
  }

}

public class LanguageDetailsChecker : BroadcastReceiver
{

  public override void OnReceive(Context context, Intent intent)
  {

    Bundle results = GetResultExtras(true);

    if (results.ContainsKey(RecognizerIntent.ExtraSupportedLanguages))
    {

       Some code

    }

  }

}

字符串
我希望返回的结果不是空的。

suzh9iv8

suzh9iv81#

如果您想在LanguageDetailsChecker的方法OnReceive上从GetResultExtras(true);获取数据,则需要在发送Broadcast时设置Bundle参数。
请参考以下代码:

private void Button_Click(object? sender, EventArgs e)
        {
            Intent intent = new Intent(RecognizerIntent.ActionGetLanguageDetails);
            //method 2
            intent.PutExtra("mykey","test_value");

            Bundle bundle = new Bundle();
            bundle.PutString("key", "bundle_string");
            //see the last parameter
            SendOrderedBroadcast(intent, null, new LanguageDetailsChecker(), null, Result.Ok, null, bundle);
        }

字符串
然后我们可以接收传递的数据如下:

[BroadcastReceiver(Enabled = true, Exported = false)]
[IntentFilter(new[] { RecognizerIntent.ActionGetLanguageDetails })]
public class LanguageDetailsChecker : BroadcastReceiver
{
    public override void OnReceive(Context? context, Intent? intent)
    {

        if (intent == null)
            return;

        Bundle bundle = GetResultExtras(true);
        if (bundle == null)
            return;
        string stringvalue = bundle.GetString("key");

        //method 2
        String value = intent.GetStringExtra("mykey");

    }
}

注:

也可以使用以下代码传递数据

intent.PutExtra("mykey","test_value");


然后在BroadcastReceiver的方法OnReceive上获取数据,如下所示:

String value = intent.GetStringExtra("mykey");

相关问题