首页 > 解决方案 > BroadcastReceiver 中的 Xamarin Android 访问变量

问题描述

我有一个broadcastReceiver检查传入意图的方法。传入intent包含一个BluetoothDevice. 在BroadcastReceiver我检查天气中,它是否正确BluetoothDevice。如果是,我想将设备的名称和 MAC 地址存储在一个变量中。

我的问题:我只能访问在我的 BroadcastReceivervariable中声明的一个。const如何访问内部的变量BroadcastReceiver

namespace firstTry3
{
[Activity(Label = "@string/app_name")]
public class bluetoothConnectionActivity : AppCompatActivity
{
    BluetoothAdapter mBluetoothAdapter;
    Button buttonBluetoothOn;
    Button buttonConnect;
    Button buttonDissconnect;
    const string deviceName = "HC-05";                  //must be changed when bluetooth Device gets new name
    string deviceMAC = "";
    const string tag = "blueApp";
    btdeviceFoundBroadcastReceiver mBtBroadcastReciever;

...

    [BroadcastReceiver(Enabled = true, Exported = true)]
    public class btdeviceFoundBroadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            // Do stuff here.
            string action = intent.Action;

            if (BluetoothDevice.ActionFound.Equals(action) && deviceMAC == "")
            {
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                string dName = device.Name;
                if (dName == deviceName)
                {
                    deviceMAC = device.Address;
                    Log.Info(tag, MethodBase.GetCurrentMethod().Name + ": bluetooth module found name: " + deviceName + " MAC: " + deviceMAC);
                }

            }
        }
    }

我无法访问 deviceMAC,出现以下错误:

“非静态字段、方法或属性 bluetoothConnectionActivity.deviceMethod 需要对象引用”

标签: c#xamarin.androidbroadcastreceiverandroid-broadcast

解决方案


推荐阅读