0
我試圖從BroadcastReceiver訪問全局活動變量(我不能使靜態)。對於這一點,我創建活動的一個實例是這樣的:在C#中獲取System.InvalidCastException
class wifiReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
MainActivity activity = (MainActivity)context.ApplicationContext;
...
,但我得到System.InvalidCastException:指定的轉換無效。在實例創建行中。我究竟做錯了什麼?
編輯:我的活動
public class MainActivity : Activity
{
private WifiManager _manager;
private List<string> _wifiSignals;
private wifiReceiver _wifiReceiver;
private TextView _Text;
protected override void OnCreate(Bundle bundle)
{
...
_wifiReceiver = new wifiReceiver();
_manager = (WifiManager)GetSystemService(Context.WifiService);
_wifiSignals = new List<string>();
if (_manager.IsWifiEnabled)
{
_manager.StartScan();
}
...
}
和更廣泛的代碼從廣播接收器的某些代碼:
public override void OnReceive(Context context, Intent intent)
{
MainActivity activity = (MainActivity)context.ApplicationContext;
activity._wifiSignals.Clear();
activity._wifiSignals.Add("Lista de wifi:\n");
IList<ScanResult> wifiScanList = activity._manager.ScanResults;
foreach (ScanResult wifiNetwork in wifiScanList)
{
activity._wifiSignals.Add(wifiNetwork.Ssid + ": " + wifiNetwork.Level);
}
//activity.presentation(activity._wifiSignals, activity);
activity._manager.StartScan();
}
爲什麼要將上下文轉換爲'MainActivity'? –
'ApplicationContext'不是'Activity'' Context',它並不是'MainActivity'。你不能做你想做的事。 –
您是否收到此行的錯誤? - 'MainActivity activity =(MainActivity)context.ApplicationContext; ' –