循环导致项目消失

时间:2017-06-07 17:45:14

标签: c# android xamarin while-loop

我正在使用c#和xamarin(Visual Studio)开发一个Android项目。我的想法是在连接到wifi时将手机静音。所以我有一个textview和一个按钮,这些是我的代码,直到现在:

AudioManager audioManager = (AudioManager)GetSystemService(Context.AudioService);
ConnectivityManager connManager = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
        NetworkInfo mWifi = connManager.GetNetworkInfo(ConnectivityType.Wifi);
            while (mWifi.IsConnectedOrConnecting)
        {
            audioManager.RingerMode = RingerMode.Silent;
        }

我的代码工作得很好,但有一些错误:当手机连接到wifi时,它会静音,但我布局中的所有项目都会消失。当手机没有连接到wifi时,它不会静音,但我的所有物品仍然在他们的位置。为什么会这样? 另外,我希望程序在后台运行,这样每当手机连接到wifi时,它都会静音。为此,我创建了这个服务类,但它似乎不起作用:

  [Service]
public class DemoService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        throw new NotImplementedException();
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        var t = new Thread(() =>
        {
            Log.Debug("DemoService", "Doing work");
            Thread.Sleep(5000);
            Log.Debug("DemoService", "Work complete");
            StopSelf();
        }
        );
        t.Start();
        return StartCommandResult.Sticky;
    }

任何帮助将不胜感激! 谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用BroadcastReceiver接收操作:android.net.wifi.STATE_CHANGE以检测连接或已连接。

WifiReceiver.cs:

[BroadcastReceiver(Enabled =true)]
[IntentFilter( new [] { "android.net.wifi.STATE_CHANGE"})]
public class WifiReceiver : BroadcastReceiver
{

    public override void OnReceive(Context context, Intent intent)
    {
       NetworkInfo info=intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo) as NetworkInfo;
        if (info != null && info.IsConnected)
        {

            ConnectivityManager manager =(ConnectivityManager) context.GetSystemService(Context.ConnectivityService);
            NetworkInfo netInfo = (NetworkInfo)manager.GetNetworkInfo(ConnectivityType.Wifi);
            AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            if (netInfo.IsConnectedOrConnecting)
            {
                Toast.MakeText(context, "Wifi is connected", ToastLength.Short).Show();
                audioManager.RingerMode = RingerMode.Silent;
            }
            else
            {
                audioManager.RingerMode = RingerMode.Normal;
            }

        }
    }
}