How to check the Internet Connection periodically in whole application?

前端 未结 1 2035
Happy的楠姐
Happy的楠姐 2020-11-30 04:05

I am doing a application which uses the Internet Connection through out the application. If the internet connection is lost while using the application, the application is f

1条回答
  •  失恋的感觉
    2020-11-30 04:45

    You should make an BroadcastReceiver that will be triggered when the connectivity status has changed :

         public class BroadCastSampleActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            this.registerReceiver(this.mConnReceiver,
                    new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
        private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
    
                NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
    
                if(currentNetworkInfo.isConnected()){
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
                }
            }
        };
    }
    

    and then in your AndroidManifest you can check if you have connectivity:

        
        
    

    Download source code - here

    0 讨论(0)
提交回复
热议问题