I was using below method for checking weather user is connected to internet or not.
public boolean internetIsConnected() {
try {
String command = "ping -c 1 google.com";
return (Runtime.getRuntime().exec(command).waitFor() == 0);
} catch (Exception e) {
return false;
}
}
Manifest is as below
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
but after I switched to latest API 30. It just freezes the app and returns false. any suggestion to get this working.
Thank you.
Edit :
As per comment's suggestions I tried below similar method but still Not working.
public boolean internetIsConnected() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
System.out.println(" mExitValue "+exitValue);
return (exitValue == 0);
} catch (IOException e){
System.out.println(" IO Error ");
e.printStackTrace(); }
catch (InterruptedException e) {
System.out.println(" Interrupted Error ");
e.printStackTrace(); }
return false;
}
I got :
I/System.out: mExitValue 1
So it is failing in Try block itself. I tried finding what Exit value "1" means but it only shows for "0" Here This Happens in both Emulator as well as physical device. Any suggestion is appreciated.
Thank you
You can check network availability using the following command.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You have to add access_network_state permission in Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Related
Below android 6.0 its working perfect, but in android marshmallow HDMI status is not coming
private boolean isHdmiSwitchSet() {
File switchFile = new File("/sys/devices/virtual/switch/hdmi/state");
if (!switchFile.exists()) {
switchFile = new File("/sys/class/switch/hdmi/state");
}
try {
Scanner switchFileScanner = new Scanner(switchFile);
Toast.makeText(MainActivity.this,"HDMI Status"+switchFileScanner.nextInt(),Toast.LENGTH_LONG).show();
int switchValue = switchFileScanner.nextInt();
switchFileScanner.close();
return switchValue > 0;
} catch (Exception e) {
return false;
}
}
Follow below steps,
First, Put storage permission in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Second, Before access file check permission allowed by user or not:
public boolean checkPermissionForWRITE_STORAGE(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
Third, do your task on true condition.
I found solution,If we will compile like android system application with android:sharedUserId="android.uid.system" its working perfect...
Thank U.
Kindly give answer,i have trouble to refresh mobile network,I don't want system app,I need only for android Mobile apps,I need to refresh my mobile data network pro grammatically in current version like marshmallow and nougat,I already put permissions for this,i attached following my codes
private static boolean setMobileConnectionEnabled(Context context, boolean enabled) {
try {
// Requires: android.permission.CHANGE_NETWORK_STATE
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
Log.i("if", "" + Build.VERSION.SDK_INT);
// pre-Gingerbread sucks!
final TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final Method getITelephony = telMgr.getClass().getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
final Object objITelephony = getITelephony.invoke(telMgr);
final Method toggleDataConnectivity = objITelephony.getClass()
.getDeclaredMethod(enabled ? "enableDataConnectivity" : "disableDataConnectivity");
toggleDataConnectivity.setAccessible(true);
toggleDataConnectivity.invoke(objITelephony);
}
// Requires: android.permission.CHANGE_NETWORK_STATE
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Log.i("else", "" + Build.VERSION.SDK_INT);
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// Gingerbread to KitKat inclusive
final Field serviceField = connMgr.getClass().getDeclaredField("mService");
serviceField.setAccessible(true);
final Object connService = serviceField.get(connMgr);
try {
final Method setMobileDataEnabled = connService.getClass()
.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
Log.i("try", "" + setMobileDataEnabled);
setMobileDataEnabled.setAccessible(true);
setMobileDataEnabled.invoke(connService, Boolean.valueOf(enabled));
} catch (NoSuchMethodException e) {
// Support for CyanogenMod 11+
final Method setMobileDataEnabled = connService.getClass()
.getDeclaredMethod("setMobileDataEnabled", String.class, Boolean.TYPE);
setMobileDataEnabled.setAccessible(true);
Log.i("catch", "" + setMobileDataEnabled);
Log.i("errr", "" + e.getMessage());
try {
setMobileDataEnabled.invoke(connService, context.getPackageName(), Boolean.valueOf(enabled));
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
}
}
// Requires: android.permission.MODIFY_PHONE_STATE (System only, here for completions sake)
else {
// Lollipop and into the Future!
final TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Log.i("telMgr",""+telMgr);
final Method setDataEnabled = telMgr.getClass().getDeclaredMethod("setDataEnabled", Boolean.TYPE);
Log.i("telMgdfgsdgr",""+setDataEnabled);
setDataEnabled.setAccessible(true);
setDataEnabled.invoke(telMgr, Boolean.valueOf(enabled));
}
return true;
} catch (NoSuchFieldException e) {
Log.e("", "setMobileConnectionEnabled", e);
} catch (IllegalAccessException e) {
Log.e("gsdjkghskd", "setMobileConnectionEnabled", e);
} catch (IllegalArgumentException e) {
Log.e("lllll", "setMobileConnectionEnabled", e);
} catch (NoSuchMethodException e) {
Log.e("nooooo", "setMobileConnectionEnabled", e);
} catch (InvocationTargetException e) {
Log.e("innnnnn", "setMobileConnectionEnabled", e);
}
return false;
}
My Manifest file
<permission
android:name="android.permission.READ_PHONE_STATE"
android:maxSdkVersion="24" />
<permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="24" />
<permission
android:name="android.permission.MODIFY_PHONE_STATE"
android:maxSdkVersion="24" />
<permission
android:name="android.permission.CHANGE_NETWORK_STATE"
android:maxSdkVersion="24" />
Kindly give some suggestions please
I can't comment so I'll put my answer here, but it might disappoint you.
There's currently no way to do that in Android >= 5.
You can do that only on rooted phone or system app. It was possible through reflection but since it was #Hide annotated Google removed it and had every right to do so.
If you're looking for disabling only (or disabling the the possibility to change cellular data state) you can use your device provider's api (like Samsung). Samsung allows to disable the possibility to change the cell data state, but... you cannot force the state back to on, after the possibility to change was turned off.
Google repeatedly ignores tickets from the community to bring back this option to SDK.
Please downvote this answer only if you have a solution how to do that without rooted phone or system app.
I am looking for a piece of code that would check network connectivity, of an Android device, including tethering, not only the wireless channels.
I have spent hours online looking for such a thing, but without any result! All the functions I found out manage only wireless net tests. Nothing with tethering. So is it at least possible? Do you have some corresponding?
this checks if Tethering is enabled. Cut from a class I changed to get adbWireless working over a tethered connection:
// check if tethering is on
try {
Method[] wmMethods = mWifiManager.getClass().getDeclaredMethods();
for(Method method: wmMethods)
if("isWifiApEnabled".equals(method.getName()))
return (Boolean) method.invoke(mWifiManager);
return false;
} catch (Exception x) {return false;}
And you also need android.permission.ACCESS_WIFI_STATE
Check this out:
public static boolean isOnline(Context context) {
boolean isOnline = false;
try {
final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if(activeNetwork != null && activeNetwork.isConnected() && activeNetwork.isAvailable()) {
isOnline = true;
} else {
isOnline = false;
}
} catch(Exception e) {
Log.e(Config.LOG_TAG, e.toString());
isOnline = false;
}
return isOnline;
}
Also add such permission into AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I have an app that works fine on a android phone , but when I try to run it on the Nexus7 which has no phone the code fails with a force stop at the location indicated. What is the solution? How do I check to see if the feature is there and what should I do to solve this?
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
printi("oopsA",6);
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
printi("oopsB",6);
boolean isMobileConn = networkInfo.isConnected(); //<<<<FAILS HERE ON NEXUS 7
Your networkInfo is probably null. You have to test that before. This means you can't access to this type of connectivityManager.
Try this:
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = false;
if(networkInfo != null)
isMobileConn = networkInfo.isConnected();
I have faced same problem with Motorola Xoom, because it does not have connectivity support for ConnectivityManager.TYPE_MOBILE.
Following code is working fine for me :
ConnectivityManager connMngr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
return connMngr.getActiveNetworkInfo().isConnected();
}
catch (NullPointerException npe) {
return false;
}
Check permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Corrected Code as follows:
IsAPhone=0;
try{
boolean isMobileConn = false;
if(networkInfo != null){ isMobileConn = networkInfo.isConnected();IsAPhone=1;}
}
catch (Exception e) {}
is there any simple way, how to check if the device is actively connected into internet (= is connected via GPRS, EDGE, UMTS, HSDPA or Wi-Fi)?
Thanks
Yes, I use isReachable.
public class Extras {
public static class Internet {
public static boolean isOnline() {
try {
InetAddress.getByName("google.ca").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
}
}
I use this in one of my apps:
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isConnected());
}
You will need these permissions in your Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can try retreaving the Local IP address to check whether device is connected to Internet.
for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumIpAddress = networkInterface.getInetAddresses(); enumIpAddress.hasMoreElements();) {
InetAddress iNetAddress = enumIpAddress.nextElement();
if (!iNetAddress.isLoopbackAddress()) {
return iNetAddress.getHostAddress().toString();
}
}
}
The return iNetAddress.getHostAddress().toString(); will give you the IP address. You need to add permission
<uses-permission android:name="android.permission.INTERNET" />
Note: If you are working in Emulator it will retun the emulator IP (generally it will be 10.0.2.15)