Thursday, July 21, 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.

1 comment:

بشير said...

Can you please give a code to make connection between android phone and robot via wifi (ip addres and port number).