2012-09-14 56 views
0
通知網絡狀態在同一活動

我與谷歌聊天應用工作使用接收器

當聊天,如果網絡出現故障時,我必須通知用戶該網絡斷開連接,如果網絡再次連接我不得不通知網絡連接在同一activity.But沒有制定出

以下是我寫的代碼:

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) 

{ 


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

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

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

    { 

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

    } 

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

    } 

    } 

}; 



protected void onPause() 

{ 


unregisterReceiver(mConnReceiver); 


super.onPause(); 


} 


protected void onResume() 

{ 

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


super.onResume(); 
} 
+0

的[如何使用服務來檢測機器人網絡狀態]可能重複(http://stackoverflow.com/questions/12405504/how-to-use-service-to-detect-network-status- in-android) – techiServices

回答

0

調用super.onResume()/ super.onPause()之前註冊/註銷接收器。

protected void onPause() 
    { 
     super.onPause(); 
     unregisterReceiver(mConnReceiver); 
    } 


    protected void onResume() 
    { 
    super.onResume(); 
    registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 

    } 
+0

非常感謝。它的工作 – user1640247