Ive written some code in an app to check if the phone has a wifi connection, I can do this fine and it works but what I actually want to check for is when the phone is not connected to wifi but it doesn't seem to be working. I think I must have the syntax wrong somewhere. please see code below:
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
myWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!myWifi.isConnected()){
//do something
}
With the ACCESS_NETWORK_STATE permission in your manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Using the getActiveNetworkInfo() method, use this method:
private boolean notConnectedToWifi(){
final ConnectivityManager conMgr = (ConnectivityManager).getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected() && activeNetwork.getType() != ConnectivityManager.TYPE_WIFI)
return true;
else
return false;
}
All you have to do next is to call the method in your condition. Example
if(notConnectedToWifi){
// Oops! You're not connected to wifi!
}
Note that I check if activeNetwork is connected via activeNetwork.isConnected() so if the device is connected to a mobile network, the method notConnectedToWifi() will return false. It will also return false if it isn't connected to any network.
try this
/* Network check */
public static boolean haveNetworkConnection(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
if (haveNetworkConnection(youractivityname.this)) {
//do your work here ..
}
You should use BroadcastReciever for getting updates of wifi connectivity in your activity. Below is the sample code
public class MainActivity extends Activity {
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Toast.makeText(MainActivity.this, "Is Wifi connected : "+wifi.isConnected(), Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initViews();
MainActivity.this.registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
}
Also write <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> permission in AndroidManifest.xml file
With the help of ConnectivityManager, you will get the network info based on trace whether WIFI is connected or not.
Check below code (pass Activity context):
public boolean IsInternetConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo nInfo = connectivity.getActiveNetworkInfo();
if (nInfo != null) {
//do your thing
if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
}
}
return false;
}
return false;
}
Related
Mission is to check if the mobile is connected on internet or not. I have problem.
It shows "Connected" even when wifi is off. Here is my class.
public class InterneProvjera {
Context context;
#SuppressLint("MissingPermission")
public InterneProvjera(Context context){
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo i: info) {
if (i.getState() == NetworkInfo.State.CONNECTED)
return true;
}
}
}
return false;
}
}
And here is in the main activity :
InterneProvjera interneProvjera = new InterneProvjera(this);
String tKonekcija = (interneProvjera.isNetworkAvailable()) ? "Connected" : "No connection";
txtIspis.setText(tKonekcija);
Sorry if its trivial question im new in android programming.
Ps: is there any Connection listener and how to check internet signal strength (3G, 4G, wifi)?
You should use BroadcastReceiver to check the network status using ConnectivityManager
Below is the code to check in your activity if network is connected or not. If connected, it will show you name of network in Toast:
ConnectivityStatusReceiver.java
public class ConnectivityStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectivityStatusReceiver connectivityStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivityStatusReceiver = new ConnectivityStatusReceiver();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityStatusReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (connectivityStatusReceiver != null) {
// unregister receiver
unregisterReceiver(connectivityStatusReceiver);
}
}
}
I have a manifest registered BroadcastReceiver that I am using to monitor WiFi disconnects. I receive a disconnect broadcast every time the device scans for WiFi. I need some way to determine if the broadcast was a result of scanning for WiFi or the device actually disconnected from a network.
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if(!intent.getAction().equals("android.net.wifi.STATE_CHANGE"))
return;
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if(networkInfo.getDetailedState() == CONNECTED || networkInfo.getDetailedState() == DISCONNECTED)
PresenceData.loadData(context);
if(networkInfo.getDetailedState() == CONNECTED) {
System.out.println("Wifi connected");
PresenceData.sendNotification("Wifi Connected", "You are now connected to " + PresenceData.getCurrentWifiSSID(context), context);
PresenceData.submitChanges(context);
} else if(networkInfo.getDetailedState() == DISCONNECTED) {
System.out.println("Wifi Disconnected");
PresenceData.sendNotification("Wifi Disconnected", "Your wifi has disconnected", context);
UpdaterService.scheduleUpdate(context);
}
}
}
}
}
You could try using NetworkInfo.State to get the current state of the network. There are enumerations for all kinds of possible states, such as failures, successes, scanning, etc. Below is a sample on how to retrieve the info:
public class MainActivity extends AppCompatActivity {
private ConnectivityManager connectivityManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.connectivityManager = (ConnectivityManager)
this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
System.out.println("Network Status " + info.getDetailedState().name());
}
}
My code
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null)
{
NetworkInfo[] info = cm.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
connectionceck();
return false;
}
private void connectionceck()
{
final AlertDialog.Builder alertDialogBuilder= new AlertDialog.Builder(HomeActivity.this);
alertDialogBuilder.setTitle("Internet NOT availablle, ");
alertDialogBuilder.setMessage("Turn on the Internet to use App Efficiently");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialogBuilder.setNeutralButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (isNetworkAvailable());
}
});
alertDialogBuilder.show();
}
try this create a simple class like this
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import com.ncrypted.connectin.R;
public class ConnectionCheck {
public boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
public AlertDialog.Builder showconnectiondialog(Context context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setIcon(R.mipmap.ic_launcher)
.setTitle("Error!")
.setCancelable(false)
.setMessage("No Internet Connection.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder;
}
}
when you need to check INTERNET is available or not than check it like this
ConnectionCheck connectionCheck= new ConnectionCheck();
if (connectionCheck.isNetworkConnected(HomeClass.this)) {
// internet is avialable
Toast.makeText(this, "Intenet Is Avialable", Toast.LENGTH_SHORT).show();
} else {
connectionCheck.showconnectiondialog(HomeClass.this).show();
}
Try this below code :
public static boolean haveNetworkConnection(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
and also add these permission in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Simple way to do it:
First, create a static method like below
/**
* Checks the device is online or not
*/
public static boolean isOnline(Context mContext) {
if (mContext != null) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
}
return false;
}
Second, add your permission to your manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage:
if (!isOnline(mContext)) {
//Not connected, Do your action
}
found a code that will check internet connectivity here
but I do not have any idea how to implement or call this class or method as I am still studying android programming using android studio.
Please see my code below and kindly let me know how to arrange it in a way that it will fire on application launch plus including the toast message stating that it is connected or not..
package com.example.enan.checkinternetconnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
private static final String LOG_TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
First of all, calling a web page and waiting for its response is NOT a good option when trying to determine whether there is or is not an available internet connection.
There are android built-in helper methods to check for connectivity such as:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Also, if what you want is to check the connectivity on application's launch, the best option is to create a new class that extends from android.app.Application and override the onCreate method as follows:
public class YourApplication extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
if (isNetworkAvailable()) {
//Connected to the Internet
} else {
//Not connected
}
}
}
Full code would look like this:
public class YourApplication extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
if (isNetworkAvailable()) {
//Connected to the Internet
} else {
//Not connected
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Finally, on your AndroidManifest.xml set the name as android:name=".YourApplication"
<application
android:name=".YourApplication"
... >
</application>
first add this permision to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then in your main Activity innitiaize the connectivity manager:
private boolean connected(){
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
And in your onCreate(Main Activities oncreate)check if user is connected.For the UI message,you can always add your own custom snackbar or dialog.
if(connected()){
Log.i("TRUE","User is connected");
}else{
Log.i("TRUE","User is not connected");
}
Call hasActiveInternetConnection(getApplicationContext()); inside onCreate method.
As a beginner, I am trying to develop an Android application, which is fetching data from server database.
Here, if Wi-Fi is not available at place, I need to turn on a 3G- or a 2G-data, which is provided on the Android device automatically or by a dialog box to turn on the mobile network.
How to check for WIFI internet connection:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
Add Permission in manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
How to Check for for mobile internet connections (3G/LTE):
boolean is3g = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
// Checks if Mobile network is available ...
if(!is3g){
// IF MOBILE CONNECTION NOT AVAILBLE, OPEN SYSTEM SETTINGS FOR MOBILE NETWORKS
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
startActivity(intent);
}
Hope this helps, please mark it as accepted answer if it worked for you.
you can check if the network is available or not, by this class
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible Internet providers
* **/
public boolean isConnectingToInternet(){
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)
{
return true;
}
}
return false;
}
}
check for internet
ConnectionDetector conn = new ConnectionDetector(youractivity.this);
if(conn.isConnectingToInternet()){
// call network operations
}else{
// Toast
}
hope this helps you
use this code to check the availability of network:-
public class CheckConnection {
private Context _context;
public CheckConnection(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
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)
{
return true;
}
}
return false;
}
}
to check network is available or not use following block of code
private boolean isNetworkAvailable(Context mContext) {
// TODO Check network connection
ConnectivityManager connMgr = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
and next do following check condition for if WIFI not available :-
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
you also required this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
// Checking for all possible internet providers
public boolean isConnectingToInternet(){
ConnectivityManager connectivity =
(ConnectivityManager) 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)
{
return true;
}
}
return false;
}
Also specify these permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
Try this:
findViewById(R.id.button).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// Check for n/w connection
if (!NetworkService
.isNetWorkAvailable(CurrentActivity.this)) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
CurrentActivity.this);
// set title
alertDialogBuilder.setTitle("Warning");
alertDialogBuilder
.setMessage("Check your network connection and try again.");
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setNegativeButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} else {
// Do your action if network exists
Intent i = new Intent(getApplicationContext(),NextActivity.class);
startActivity(i);
}
}
});
NetworkService.java:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class NetworkService {
private NetworkService() {}
public static boolean isNetWorkAvailable(final Context contextActivity) {
ConnectivityManager conMgr = (ConnectivityManager) contextActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
Add these permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />