check internet in android emulator [duplicate] - java

This question already has answers here:
How to check the internet connectivity within the network in Android (using internet of some other device through HOTSPOT)
(2 answers)
Closed 8 years ago.
i am trying to check internet connection in my android app
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.d("Network",
"NETWORKnAME: " + info[i].getTypeName());
return true;
}
}
return false;
}
but problem is that when i try to check internet connection in emulator by turning off host PC internet connection still this function returning true that is internet available while i have turn off internet connection from host PC
ConnectivityManager class help in determining whether connected with the network not about the internet connectivity
my question is how to check internet connection is not available ?

Try again after turning off wifi and data package..hope this helps.

Try this to detect your internet connection
public static boolean isInternetConnected(Context mContext) {
try {
ConnectivityManager connect = null;
connect = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connect != null) {
NetworkInfo resultMobile = connect
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo resultWifi = connect
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((resultMobile != null && resultMobile
.isConnectedOrConnecting())
|| (resultWifi != null && resultWifi
.isConnectedOrConnecting())) {
return true;
} else {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Add the following permissions to your manifest file,
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

How should I go ahead and check mobile data connectivity

I need a message to show up if there is no internet connection. Currently, if wifi is turn off then the toast method will work and won't move forward. However, if i turn on my mobile data even without a service plan, it will still open a blank activity.
here is the code i got from here
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
and this below is in my onClick method.
newsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(CheckNetwork.isInternetAvailable(MainActivity.this)) //returns true if internet available
{
moveToNews();
}
else
{
Toast.makeText(MainActivity.this,"Please Check Your Internet Connection and Try Again",Toast.LENGTH_LONG*4000).show();
}
To check internet connection -
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
In Menifest file -
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
check my below code
[1].Add below line internet permission into AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
[2]. On your MainActivity or Parent activity from you want to display or going to next activity add below code
[2.1] Globally declare below variable
private boolean isInternetConnected;
[2.2] add below line into onCreate()
isInternetConnected = isNetworkConnected(getApplicationContext());
[2.3] add below method
public boolean isNetworkConnected(Context context)
{
if(context != null)
{
ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else
return true;
}
else
{
return true;
}
}
else
{
return true;
}
}
[3]. add below code into onCreate() below of this line isInternetConnected = isNetworkConnected(getApplicationContext());
if(isInternetConnected){
//Move to another Activity or display Toast
}
else{
//Toast of not connected with Internet
}
THAT'S IT ;)!!

Allow switch to toggle only if internet connection is available

I have used a switch in my android code.
If internet service is available then only allow toggle else show a toast message. How do I achieve this?
I am unable to do so using
switch.setOnCheckedChangeListener().
The check is working only if I press the switch button twice.
aSwitch.setEnabled(false);
works only after I click once
First create a boolean that carries a flag :
boolean checkInternetFlag = false;
Then create a method that check if internet is available like this for example:
public final boolean isInternetOn() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need to add this permission in your manifest :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then you can do what you want in a condition like this :
checkInternetFlag = isInternetOn();
if (!checkInternetFlag) {
Toast.makeText(getActivity(), "Internet not available", Toast.LENGTH_LONG).show();
}
Also you can disable your toggle switch like this :
aSwitch.setEnabled(false);
And to make switch not clickable use :
aSwitch.setClickable(false);
The following method will catch if there is a change occured to networkstate:
1)Add this code to onCreate():
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
2) Add OnDestroy() Method:
#Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();
unregisterReceiver(receiver);
}
3) Add the Following Code to your activity:
public class NetworkChangeReceiver extends BroadcastReceiver
{
#Override
public void onReceive(final Context context, final Intent intent)
{
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context)
{
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
if(!isConnected)
{
Log.v(LOG_TAG, "Now you are connected to Internet!");
aSwitch.setEnabled(true);
isConnected = true;
}
return true;
}
}
}
}
Toast.makeText(YourActivity.this, "Internet is not available", Toast.LENGTH_SHORT).show();
aSwitch.setEnabled(false);
isConnected = false;
return false;
}
}
4)Add this permission in your manifest file :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Hopefully this relates to your requirement.

How can I monitor for changes to mobile data being enabled on Android?

I have successfully used the answer to this question to perform a one off check if mobile data is enabled, but I would like to receive a notification of such change, for example when a user goes to this screen:
Is this possible?
You can use OnNetworkActiveListener to monitor activation of network data. The ConnectivityManager class can give you infos on the currently active network connection. It would go like this :
ConnectivityManager cm = getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfos networkInfos = cm.getActiveNetworkInfo();
if(networkInfos.isConnected()){
//Do something
} else {
//Do something else
}
Hope it helps.
public static boolean isNetworkOn(Context context, int networkType) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= 21) {
final Network[] networks = connectivityManager.getAllNetworks();
for (Network network : networks) {
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == networkType && networkInfo.isConnectedOrConnecting()) {
return true;
}
}
}
else {
#SuppressWarnings("deprecation") final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(networkType);
if (networkInfo.isConnectedOrConnecting()) {
return true;
}
}
return false;
}

wait until wifi connected on android

I have a small program that trying to connect to a wifi network.
It enables the wifi on the device then if it's the first time that is connect to the certain networkss It loads the device wifi in order to select and add the password for connection.
Until I add the password in order to connect the program should not be finished.
How can I add something to wait until I get from the wifi manager that is connected?
I try sleep but it freeze the application and am not getting the wifi pop up menu to connect?
are there any other ways?
I have found the solution for your problem a month ago, just use Thread put method isConnected() in it. In this case, I use WifiExplorerActivity to display all wifi network and allow user connect to it.
Thread t = new Thread() {
#Override
public void run() {
try {
//check if connected!
while (!isConnected(WifiExplorerActivity.this)) {
//Wait to connect
Thread.sleep(1000);
}
Intent i = new Intent(WifiExplorerActivity.this, MainActivity.class);
startActivity(i);
} catch (Exception e) {
}
}
};
t.start();
And this is function to check wifi has connected or not:
public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED;
}
Finally, make sure your Androidmanifest.xml look like this:
<activity android:name=".WifiExplorerActivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</activity>
Also, you can use ProgressDialog to wait connect. See http://developer.android.com/guide/topics/ui/dialogs.html

how to check wifi or 3g network is available on android device

Here, my android device supports both wifi and 3g. At particular time which network is available on this device. Because my requirement is when 3g is available I have to upload small amount of data. when wifi is available entire data have to upload. So, I have to check connection is wifi or 3g. Please help me. Thanks in advance.
I use this:
/**
* Checks if we have a valid Internet Connection on the device.
* #param ctx
* #return True if device has internet
*
* Code from: http://www.androidsnippets.org/snippets/131/
*/
public static boolean haveInternet(Context ctx) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return false;
}
return true;
}
You also need
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in AndroidMainfest.xml
To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
To get the type of the mobile network I would try TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName
You need to add below permission in android manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
After that you can use below functions to check wifi or mobile network is connected or not
public static boolean isWifiConnected(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return ((netInfo != null) && netInfo.isConnected());
}
public static boolean isMobileConnected(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return ((netInfo != null) && netInfo.isConnected());
}
Some references from developer.android.com are:
https://developer.android.com/reference/android/net/ConnectivityManager.html
https://developer.android.com/reference/android/net/NetworkInfo.html
https://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo()
First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device.
You'll need the ACCESS_NETWORK_STATE permission to use this service.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi.isAvailable() == true) {
return "Connected to WiFi";
} else if (mMobile.isAvailable() == true) {
return "Connected to Mobile Network";
} else return "No internet Connection"
You can use this method to check whether your internet connection is 2G, 3G or 4G:
public String getNetworkClass(Context context) {
TelephonyManager mTelephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int networkType = mTelephonyManager.getNetworkType();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
return "4G";
default:
return "Unknown";
}
}
And using following method you can check if internet is available or not, and get whether you are accessing the internet via a mobile network or WiFi:
public String getNetworkType(Context context){
String networkType = null;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
networkType = "WiFi";
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
networkType = "Mobile";
}
} else {
// not connected to the internet
}
return networkType;
}

Categories

Resources