Allow switch to toggle only if internet connection is available - java

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.

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

How to detect Network change and change activity from A to B when Network is connected

I have SplashActivity, Activity A and Activity B.
When the Internet is not available, Splash activity redirects to Activity A and when Internet is available and is connected SplashActivity redirects to Activity B.
I would like to immediately close the Activity A when user is connected itself and Open Activity B when user is still inside the app and he open his wifi or mobile Data.
Here is the code I'm using in SplahsActivity to redirect to Activity A and Activity B as per Network status
public static boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
and I check with
if (isNetworkStatusAvialable(getApplicationContext())) {
// Load Activity B
} else {
Load Activity A and Toast Message, " No Internet"
}
Thanks in advance.
In this case you should check network status using BroadcastReceiver because you immediately want to close current activity and move to other activity. So below is complete code for it:
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();
// Your code to start Activity B
Activity activity = (Activity) context;
intent = new Intent(activity, ActivityB.class);
activity.startActivity(intent);
} 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);
}
}
}
To close Activity A you just add android:noHistory="true" in Manifest like below:
<activity android:label="#string/app_name" android:name="ActivityA"/>
Hope this will help you.

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

NetworkChangeReceiver's onReceive method is called multiple times when 3G and WIFI are enable at same time

I'm developing an android application and I have the next problem:
I implemented Broadcast receiver for connectivity change and the method onReceive seems to be called 4 times in a row when 3G and Wifi are enabled at the same time.
So my question is:
Is there a way listen only for internet connection, not for network change?
Or is there any way for the method onReceive to be called only once when 3G and Wifi are enable at the same time?
Here is my code:
public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkMonitoring";
#Override
public void onReceive(Context context, Intent intent) {
if (isOnline(context)) {
Log.v(TAG, "Connected!");
// update(context);
} else {
Log.v(TAG, "Not connected!");
// stopUpdate(context);
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
return true;
return false;
}
}
In the Android Manifest:
<receiver android:name="xxxxx.xxxxx.xxxxx.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Here is the log:
05-06 16:24:05.985: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.250: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.720: V/NetworkMonitoring(569): Connected!
05-06 16:24:11.031: V/NetworkMonitoring(569): Connected!
(Notice the time!)
I had the same problem with the same type of broadcast receiver.
Searched a little and found a workaround.
BroadcastReceiver receives multiple identical messages for one event
Edit:
The workaround is to use a flag that tells you when is the first time onReceive is being invoked.
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static boolean firstConnect = true;
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
if(firstConnect) {
// do subroutines here
firstConnect = false;
}
}
else {
firstConnect= true;
}
}
}
Hope it helps.

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