How should I go ahead and check mobile data connectivity - java

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 ;)!!

Related

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.

what is the best way to check Internet connection continuously in android

I am developing an application. In that one screen check Internet connection, immediately after onCreate() method. If network connection is good i am calling one AsyncTask class for load countries list and show it on screen in spinnerView. If there is no network connection i am showing Toast Message to User and call check_Network(AsyncTask). In this class protected Long doInBackground(URL... params) method i'm checking Network connected or not if connected call countries AsyncTask otherwise again i am calling check_Network(AsyncTask). this process repeat until network is connected. my problem is It is correct way for Check Network Repeatedly. please suggested me. sorry i am poor in english please understand.blow i am showing my code
if (CheckNetwork.isOnline(this)) {
try {
new CountryProcess().execute();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(
getApplicationContext(),
getString(R.string.network_connection_fail)
+ "!", Toast.LENGTH_LONG).show();
new NetWork_connectivity().execute();
}
//.......................//
class NetWork_connectivity extends AsyncTask<URL, Integer,Long>
{
#Override
protected Long doInBackground(URL... params)
{
if (CheckNetwork.isOnline(MainActivity.this)) {
new CountryProcess().execute();
}else
{
new NetWork_connectivity().execute();
}
return null;
}
}
Add below code in manifest, for adding receiver with connectivity change intent
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And at receiver side, get extras associated with intent and check for status. So whenever there is change in network status, you will be notified then perform your task accordingly.
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
//connected
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
//not connected
}
}
}
For your case, you would like to add permission in manifest and register receiver in your activity.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);
Make sure to unregister it as well before leaving activity with
unregisterReceiver(networkReceiver);
private BroadcastReceiver networkReceiver = new BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
//connected
}
}
//not connected
}
}
And based upon your requirement that you requires connected status only one time. First check for connectivity and if not connected then only register receiver.
public boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
To access internet we need INTERNET Permission
To detect network status we need ACCESS_NETWORK_STATE Permission
Add these lines in your AndroidManifest.xml:
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Create this method in your java class:
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;
}
When ever you want to check Internet Status in your application call isConnectingToInternet() function and it will return true or false
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false

Android check WIFI status (disconnected or user changed WIFI) How to FLAG it?

I is there a way to Flag if a WIFI connection got disconnected/ dropped off OR if the user actually changed the WIFI network ?
I need my app to do :
Connect to a WIFI XYZ, if XYZ get disconnect (FLAG 1) or dropped off Then reconnect to XYZ.
But is the user change to another wifi BTOpen (FLAG 2) then allow the connect and Stop my service.
If user connect to XYZ again then start the loop again.
What I got so far is :
<!-- WIFI Receiver -->
<receiver android:name=".ReceiverWifi" >
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service android:name=".ServiceWifiMonitor" />
<receiver android:name=".ServiceController" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
BroadcastReceiver:
myApplication = (MyApplication) context.getApplicationContext();
conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
networkInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isConnected = networkInfo != null && networkInfo.isConnected();
int reconnectedCount = myApplication.getReconnectedCount();
if (wifiManager.isWifiEnabled()) {
if("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
//Start and Stop Service
if(myApplication.isReconnect()) startServiceWifiMonitor(); else stopServiceWifiMonitor();
if (isConnected) {
//There is a WIFI Connection
myApplication.setConnectedWifi(NetworkUtil.getCurrentSSID(context));
myApplication.setWifiStatus("connected");
if (NetworkUtil.isConnectedToXYZ(context)) {
startServiceWifiMonitor();
if(pref.getisFirstTime())
{
myApplication.setWifiByChoise("XYZ");
pref.setisFirstTime(false);
}
else { myApplication.setisReconnect(true); }
}
else {
//Connected to different NetWork
if(myApplication.isReconnect() && NetworkUtil.isXYZAvailable(context))
{
//ReConnect to XYZ
NetworkUtil.connectToXYZ(context);
myApplication.setReconnectedCount(reconnectedCount++);
}
else { resetValues("AAAA"); }
}
}//end if
else
{
if(NetworkUtil.isXYZAvailable(context) && myApplication.getWifiByChoise().equals("XYZ"))
{
NetworkUtil.connectToXYZ(context);
myApplication.setReconnectedCount(reconnectedCount++);
}
else { resetValues(""); }
}
}//end CONNECTIVITY_CHANGE
Service Monitor:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand > Received start id " + startId + ": " + intent);
objHandler.postDelayed(mTasks, 1000);
return START_STICKY;
}//end onStartCommand
private Runnable mTasks = new Runnable() {
public void run() {
if(myApplication.getWifiByChoise().equals("XYZ") && NetworkUtil.isXYZAvailable(context)) {
try
{
//Get the numbers of Reconnection
int count = myApplication.getReconnectedCount();
if(!NetworkUtil.isWifiConnected(context))
{
NetworkUtil.connectToXYZ(context);
myApplication.setisReconnect(true);
myApplication.setReconnectedCount(count++);
}
if(!NetworkUtil.isConnectedToXYZ(context))
{
NetworkUtil.connectToXYZ(context);
myApplication.setisReconnect(true);
myApplication.setReconnectedCount(count++);
}
} catch (Exception e) {e.printStackTrace();}
}
else { stopSelf(); }
int ms_interval = 3000;
objHandler.postDelayed(mTasks, ms_interval);
}
};//end Runnable mTasks
The problem with my app is that :
It crashed the device, Seems like its eating up all the memory ram.
sometimes with the wifi XYZ get disconnect it wont connect again and if user change to another wifi, it won't allow the connection.
I really appreciate your help. Thank you.
Check the network connected Name by using:
public String getWifiName(Context context) {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (manager.isWifiEnabled()) {
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo != null) {
DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
return wifiInfo.getSSID();
}
}
}
return null;
}
if this name matches your networkSSID, i.e. XYZ, then resume the service, else if it doesn't match, then stop the service:
if getWifiName(this).compareTo("XYZ") == 0 { //XYZ is your network name on which you want to resume the service
//code to resume
} else {
//code to stop the service
}
This is how I handle it in my app:
public class WifiStateWatcher extends BroadcastReceiver {
private MainActivity activity;
public WifiStateWatcher(MainActivity activity) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
}
#Override
public void onReceive(Context context, Intent intent) {
SupplicantState supState;
WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
if (supState.equals(SupplicantState.COMPLETED)) {
//we are connected to Wi-Fi network
} else {
//we lost Wi-Fi connectivity
}
}
}
You will need android.permission.ACCESS_WIFI_STATE permission
What you have done is almost correct. you need to check the network ssd name with the user connected wifi name.If it matched then do your part.
WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
WifiInfo networkInfo = wifiManager.getConnectionInfo();
if (networkInfo != null) {
DetailedState state = WifiInfo.getDetailedStateOf(networkInfo .getSupplicantState());
if (state == DetailedState.CONNECTED ) {
return networkInfo.getSSID();
}
}
}
return null;
Now you have the network SSID so try to check with the your wifi name and SSID then you will get to know the connection status.....
Happy Programming
Also just checked this and found out that the main difference is:
/** IP traffic should be available. */
DetailedState.CONNECTED
and:
/**
* …
* This state indicates that the supplicant has completed its
* processing for the association phase and that data connection is
* fully configured. Note, however, that there may not be any IP
* address associated with the connection yet. Typically, a DHCP
* request needs to be sent at this point to obtain an address.
*/
SupplicantState.COMPLETED
So to trust that wifi is completely up, i now added the checks that:
boolean isConnected = activeNetworkInfo.isConnected();
and DetailedState.CONNECTED :)
happy coding

check internet in android emulator [duplicate]

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" />

How to reliably detect an Internet connection at Android phone wake up

I have an App that relies on Internet connection at startup, and I am able to detect that ok with the code below.
However when the phone has been idle for some time and I unlock it and start my app it does not find the connection immediately and I have to re-start the app again to get success.
I have tried waiting in a thread and retrying the code below again with no success too.
Any ideas would be appreciated, thank you.
Code
// check Network/Internet connection
public boolean isOnline() {
try {
ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
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;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return false;
}
Put your code in the onResume() of your activity. That way it'll be checked each time you return to the activity.
Additionally, add a flag to know whether to check for the connection, and set that flag to true in the onPause() of your activity. Reset it to false in your onResume().
Something like:
boolean check;
protected void onCreate(Bundle blah) {
super(blah);
check = true;
// whatever else
}
protected void onResume() {
if(check) {
isOnline();
// Everything else
check = false;
}
super.onResume();
}
protected void onPause() {
check = true;
super.onPause();
}
EDIT: onResume() won't be called unless this activity is.. well being resumed, so you could just add:
protected void onResume() {
isOnline();
// Everything else
super.onResume();
}
Look at this flow chart from the Android dev site for a better understanding:

Categories

Resources