2016-05-12 76 views
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(); 
     } 
+0

爲什麼要將上下文轉換爲'MainActivity'? –

+0

'ApplicationContext'不是'Activity'' Context',它並不是'MainActivity'。你不能做你想做的事。 –

+0

您是否收到此行的錯誤? - 'MainActivity activity =(MainActivity)context.ApplicationContext; ' –

回答

0

雖然我記得在以前的應用我公司開發的另一個活動調用MainActivity性質,我m很確定你不能調用像你嘗試使用StartScan()一樣的函數。 我通常使用的選項是存儲序列化的數據,並在Main中調用它。 我做像一些方法的類:

class persistence 
{ 
    ISharedPreferences prefs; 
    ISharedPreferencesEditor editor; 

    public persistence(Context cont) 
    { 
     prefs = PreferenceManager.GetDefaultSharedPreferences(cont); 
     editor = prefs.Edit(); 
    } 
    public void store(List<articulo> articulos) 
    { 
     string raw = JsonConvert.SerializeObject(articulos); 
     editor.PutString("articulos", raw); 
     editor.Commit(); 
    } 

    public List<articulo> recover() 
    { 
     string raw = prefs.GetString("articulos", null); 
     List<articulo> lista; 
     if (raw == null) 
      lista = new List<articulo>(); 
     else 
      lista = JsonConvert.DeserializeObject<List<articulo>>(raw); 
     return lista; 
    } 
} 

在你的onReceive功能我打電話到店裏功能 在你的OnCreate功能,您可以直接做

persistence datos; 
protected override void OnCreate(Bundle bundle) 
{ 
    _wifiReceiver = new wifiReceiver(); 
    _manager = (WifiManager)GetSystemService(Context.WifiService); 
    datos = new persistence (this); 
    _wifiSignals = datos.recover(); 
    if(_wifiSignals.Count>0) 
     StartScan(); 
} 

這也將數據從一個存如果你不想在調用BroadcastReceiver之後清除持久性數據,