2015-06-03 11 views
11

C'è un modo per contrassegnare se una connessione WIFI è stata disconnessa/interrotta O se l'utente ha effettivamente cambiato la rete WIFI?Controllo Android Stato WIFI (scollegato o utente modificato WIFI) Come contrassegnarlo?

Ho bisogno della mia app da fare: Connettersi a una XYZ WIFI, se XYZ si disconnette (FLAG 1) o si disconnette Quindi riconnessione a XYZ. Ma l'utente passa a un altro BTOpen wifi (FLAG 2), quindi consente la connessione e interrompe il servizio. Se l'utente si collega nuovamente a XYZ, riavvia il ciclo.

Che cosa ho ottenuto finora è:

<!-- WIFI Receiver --> 
    <receiver android:name=".ReceiverWifi" > 
     <intent-filter> 
      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> 
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
     </intent-filter> 
    </receiver> 
    <service android:name=".ServiceWifiMonitor" /> 
    <receiver android:name=".ServiceController" > 
     <intent-filter > 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      <category android:name="android.intent.action.QUICKBOOT_POWERON" /> 
     </intent-filter> 
    </receiver> 

BroadcastReceiver:

myApplication = (MyApplication) context.getApplicationContext(); 
    conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    networkInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 


    boolean isConnected = networkInfo != null && networkInfo.isConnected(); 
    int reconnectedCount = myApplication.getReconnectedCount(); 


    if (wifiManager.isWifiEnabled()) { 


     if("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) { 


      //Start and Stop Service 
      if(myApplication.isReconnect()) startServiceWifiMonitor(); else stopServiceWifiMonitor(); 



      if (isConnected) { 
       //There is a WIFI Connection 
       myApplication.setConnectedWifi(NetworkUtil.getCurrentSSID(context)); 
       myApplication.setWifiStatus("connected"); 




       if (NetworkUtil.isConnectedToXYZ(context)) { 
        startServiceWifiMonitor(); 

        if(pref.getisFirstTime()) 
        { 
         myApplication.setWifiByChoise("XYZ"); 
         pref.setisFirstTime(false); 
        } 
        else { myApplication.setisReconnect(true); } 
       } 
       else { 
        //Connected to different NetWork 
        if(myApplication.isReconnect() && NetworkUtil.isXYZAvailable(context)) 
        { 
         //ReConnect to XYZ 
         NetworkUtil.connectToXYZ(context); 
         myApplication.setReconnectedCount(reconnectedCount++); 
        } 
        else { resetValues("AAAA"); } 
       } 


      }//end if 
      else 
      { 
       if(NetworkUtil.isXYZAvailable(context) && myApplication.getWifiByChoise().equals("XYZ")) 
       { 
        NetworkUtil.connectToXYZ(context); 
        myApplication.setReconnectedCount(reconnectedCount++); 
       } 
       else { resetValues(""); } 
      } 
     }//end CONNECTIVITY_CHANGE 

Service Monitor:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.i(TAG, "onStartCommand > Received start id " + startId + ": " + intent); 

     objHandler.postDelayed(mTasks, 1000); 

    return START_STICKY; 
}//end onStartCommand 



private Runnable mTasks = new Runnable() { 
    public void run() { 

     if(myApplication.getWifiByChoise().equals("XYZ") && NetworkUtil.isXYZAvailable(context)) {    
      try 
      { 
       //Get the numbers of Reconnection 
       int count = myApplication.getReconnectedCount(); 

       if(!NetworkUtil.isWifiConnected(context)) 
       { 

        NetworkUtil.connectToXYZ(context); 
        myApplication.setisReconnect(true); 
        myApplication.setReconnectedCount(count++); 
       } 

       if(!NetworkUtil.isConnectedToXYZ(context)) 
       { 

        NetworkUtil.connectToXYZ(context); 
        myApplication.setisReconnect(true); 
        myApplication.setReconnectedCount(count++); 
       } 
      } catch (Exception e) {e.printStackTrace();} 
     } 
     else { stopSelf(); } 
     int ms_interval = 3000; 
     objHandler.postDelayed(mTasks, ms_interval); 
    } 
};//end Runnable mTasks 

Il problema con la mia app è che: E 'caduto il dispositivo Sembra che mangi tutta la ram della memoria. a volte con il wifi XYZ si disconnette, non si connetterà di nuovo e se l'utente passa a un altro wifi, non permetterà la connessione.

Apprezzo molto il vostro aiuto. Grazie.

risposta

6

Controllare il nome collegato rete utilizzando

public String getWifiName(Context context) { 
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    if (manager.isWifiEnabled()) { 
     WifiInfo wifiInfo = manager.getConnectionInfo(); 
     if (wifiInfo != null) { 
      DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()); 
      if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) { 
       return wifiInfo.getSSID(); 
      } 
     } 
    } 
    return null; 
} 

se questo nome corrisponde al networkSSID, cioè XYZ, di riprendere il servizio, altrimenti se non corrisponde, di interrompere il servizio

if getWifiName(this).compareTo("XYZ") == 0 { //XYZ is your network name on which you want to resume the service 
    //code to resume 
} else { 
    //code to stop the service 
} 
3

Questo è come mi occupo nel mio app:

public class WifiStateWatcher extends BroadcastReceiver { 

    private MainActivity activity; 

    public WifiStateWatcher(MainActivity activity) { 
     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 
    } 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     SupplicantState supState; 
     WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE); 
     WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
     supState = wifiInfo.getSupplicantState(); 

     if (supState.equals(SupplicantState.COMPLETED)) { 
      //we are connected to Wi-Fi network 
     } else { 
      //we lost Wi-Fi connectivity 
     } 
    } 
} 

avrete bisogno android.permission.ACCESS_WIFI_STATE perm ission

0

Quello che hai fatto è quasi corretto. è necessario controllare il nome ssd della rete con il nome wifi connesso all'utente. Se corrisponde, fare la propria parte.

WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
if (wifiManager.isWifiEnabled()) { 
    WifiInfo networkInfo = wifiManager.getConnectionInfo(); 
    if (networkInfo != null) { 
     DetailedState state = WifiInfo.getDetailedStateOf(networkInfo .getSupplicantState()); 
     if (state == DetailedState.CONNECTED) { 
      return networkInfo.getSSID(); 
     } 
    } 
} 
return null; 

Ora avete l'SSID della rete in modo da cercare di controllare con il vostro nome e wifi SSID poi si arriva a conoscere lo stato della connessione ..... Felice Programmazione

0

anche appena controllato questo e scoperto che la differenza principale è:

/** IP traffic should be available. */ 
DetailedState.CONNECTED 

e:

/** 
* … 
* This state indicates that the supplicant has completed its 
* processing for the association phase and that data connection is 
* fully configured. Note, however, that there may not be any IP 
* address associated with the connection yet. Typically, a DHCP 
* request needs to be sent at this point to obtain an address. 
*/ 
SupplicantState.COMPLETED 

Quindi, per fiducia che la connessione wifi è completamente, ora aggiunto i controlli che:

boolean isConnected = activeNetworkInfo.isConnected(); 

e DetailedState.CONNECTED :)

felice di codifica

Problemi correlati