Thursday, 21 July 2011

Check Network Connectivity

To check network connectivity, we can use ConnectivityManager to get info of active network.

Check Network Connectivity

package com.exercise.AndroidNetworkConnectivity;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class AndroidNetworkConnectivityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

if (activeNetworkInfo == null){
Toast.makeText(AndroidNetworkConnectivityActivity.this,
"No Active Network",
Toast.LENGTH_LONG).show();
}else{
if (activeNetworkInfo.isConnected()){
Toast.makeText(AndroidNetworkConnectivityActivity.this,
"network is Connected",
Toast.LENGTH_LONG).show();
}else if (activeNetworkInfo.isConnectedOrConnecting()){
Toast.makeText(AndroidNetworkConnectivityActivity.this,
"network is Connecting",
Toast.LENGTH_LONG).show();
}
}
}
}


Remark: uses permission of "android.permission.ACCESS_NETWORK_STATE" is needed.

No comments:

Post a Comment