2012-09-13 68 views
0

我正在使用BroadCastReceiver來監視活動的網絡狀態。但它沒有解決。任何人都可以幫助我。如何使用服務來檢測android中的網絡狀態

import android.app.ListActivity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Bundle; 
import android.widget.Toast; 

public class GTChat extends ListActivity { 

    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

    } 

    // ///////////////////////////////////////////////////////////////// 

    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() 

    { 

     @Override 
     public void onReceive(Context context, Intent intent) 

     { 

      NetworkInfo info = (NetworkInfo) intent 
        .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); 

      if (info.getState().equals(NetworkInfo.State.CONNECTED)) 

      { 

       GTalkChatDetails.chat(getApplicationContext()); 
       GTalkChatDetails.adddMsgListener(getApplicationContext()); 

      } 

      else 

      { 

       Toast.makeText(getApplicationContext(), 
         "Network not connected", Toast.LENGTH_LONG).show(); 

      } 

     } 

    }; 

    // ////////////////////////////////////////////////// 

    protected void onPause() 

    { 

     unregisterReceiver(mNetworkReceiver); 

     super.onPause(); 

    } 

    protected void onResume() 

    { 

     registerReceiver(mNetworkReceiver, new IntentFilter(
       ConnectivityManager.CONNECTIVITY_ACTION)); 

     super.onResume(); 

    } 
} 

回答

0

嘗試使用此代碼段:

private boolean isNetworkAvailable() { 
ConnectivityManager connectivityManager 
     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
return activeNetworkInfo != null; 
} 

你不是註冊在清單廣播接收器,它應該做的。 或將其更改爲此類

private final BroadcastReceiver mConnReceiver = new BroadcastReceiver() { 
    @Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); 

    // your check here 

}}