2017-10-09 35 views
0

我是Xamarin新手。我有以下的對話片段:Xamarin。如何在循環中顯示對話框?

public class EnableGpsDialog : DialogFragment 
{ 
    public static EnableGpsDialog newInstance() 
    { 
     EnableGpsDialog d = new EnableGpsDialog(); 
     return d; 
    } 

    override public Dialog OnCreateDialog(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 
     var builder = new AlertDialog.Builder(Activity); 
     var title = "Please, enable GPS"; 
     builder.SetTitle(title); 
     builder.SetPositiveButton("OK", EnableGpsAction); 
     var dialog = builder.Create(); 
     dialog.SetCanceledOnTouchOutside(false); 
     return dialog; 
    } 

    private void EnableGpsAction(object sender, DialogClickEventArgs e) 
    { 
     var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings); 
     StartActivity(intent); 
    } 
} 

它運作良好,但我需要這個對話框,而GPS是禁用顯示。 我該如何做到這一點? 我的方法(它顯示什麼):

private void EnableGps() 
    { 
     LocationManager locationManager = null; 
     while (true) 
     { 
      locationManager = (LocationManager)GetSystemService(Context.LocationService); 
      if (locationManager.IsProviderEnabled(LocationManager.GpsProvider)) 
      { 
       return;//gps is enabled 
      } 
      else 
      { 
       //show dialog 
       EnableGpsDialog gpsDialog = new EnableGpsDialog(); 
       var transaction = FragmentManager.BeginTransaction(); 
       gpsDialog.Show(transaction, "Enable GPS dialog fragment"); 
      } 
     } 
    } 

回答

1

您應該使用監控定位服務,而不是試圖調查外景經理變化的廣播接收器。

註冊一個運行時接收器:

ApplicationContext.RegisterReceiver(
    new GPSEnabledReceiver(ApplicationContext, GPSEnabledHandler), 
    new IntentFilter(LocationManager.ProvidersChangedAction) 
); 

處理您的片段在事件的變化:

public void GPSEnabledHandler(object sender, EventArgs e) 
{ 
    Log.Debug("SO", "GPS Enabled"); 
} 

的BroadcastReceiver的子類:

public class GPSEnabledReceiver : BroadcastReceiver 
{ 
    readonly Context context; 
    readonly EventHandler locationEvent; 

    public GPSEnabledReceiver(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer) { } 

    public GPSEnabledReceiver() {} 

    public GPSEnabledReceiver(Context context, EventHandler locationEvent) 
    { 
     this.context = context; 
     this.locationEvent = locationEvent; 
    } 

    public override void OnReceive(Context context, Intent intent) 
    { 
     if (context?.GetSystemService(LocationService) is LocationManager locationManager && locationManager.IsProviderEnabled(LocationManager.GpsProvider)) 
     { 
      locationEvent?.Invoke(this, new EventArgs()); 
     } 
    } 
}