2013-10-10 62 views
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 { 


     } 

回答

1

這個輔助類也許能幫助你

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

主要runInBackgroundThenUi()方法,把那個等待的WiFi中的代碼可運行在後臺PARAM,然後將代碼在ui參數中連接wifi後運行。

像這樣

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

聲明,我寫了這個類。儘管我使用了很多(全部)應用程序。

+0

謝謝。有用!這個類應該包含在Android的API中。 – Kristopher

+0

嗨感謝幫助類,我有一個問題,我檢查網絡連接使用連接管理器,並返回true&在我的應用程序中使用**如果語句**返回值,然後從網絡更新我的應用程序。我得到的問題是,如果在返回到if語句之後網絡關閉,我的應用程序將繼續永久運行而不退出。我能做什麼? –