1

我编写了启动 wifi 的代码,然后(每秒)检查 wifi 是否已连接。问题是它持有主线程,直到连接可用。我需要帮助处理此代码。

// Sevice
// wifi checking part
    ConnectivityManager Cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo Ni = Cm.getActiveNetworkInfo();
    WifiManager wiM = (WifiManager) getSystemService(WIFI_SERVICE);
    wiM.setWifiEnabled(true);


        int i=0;

        while (Ni == null)   {
           Ni = Cm.getActiveNetworkInfo();
            i++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (i > 29) {
                break;
            }
        }

        if(Ni.isConnected())    {

            Intent intent1 = new Intent(this, MainActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent1, 0);

            noti = new NotificationCompat.Builder(this)
                    .setContentTitle("app")
                    .setContentText("running")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentIntent(pendIntent)
                    .setPriority(Notification.PRIORITY_MIN)
                    .build();

            startForeground(12345, noti);

            new myTask().execute(httpAddress);
            DelayedShutdown(millis);

        } else {


        }
4

1 回答 1

1

这个助手类也许可以帮助你

https://gist.github.com/bclymer/6708605

主要是runInBackgroundThenUi()方法,把等待wifi的代码放到一个runnable的background参数中,然后wifi连接后运行的代码放到ui参数中。

像这样

ThreadManager.runInBackgroundThenUi(new Runnable() {
    @Override
    public void run() {
        // wait for that tasty WiFi
    }
}, new Runnable() {
    @Override
    public void run() {
        // GUYS I HAVE THE WIFI!!
    }
});

免责声明,我写了这门课。不过,我在很多(所有)应用程序中都使用了它。

于 2013-10-10T18:58:25.407 回答