This question already has answers here:
How to check internet access on Android? InetAddress never times out
(64 answers)
Closed 5 years ago.
I'm using Firebase. Some features of my app can't using was offline (or maybe offline mode can make in future). So how I can detect of connection was lost, or wifi/otherNetwork is off while running activity. I following this doc but only use when start app... not working on running app. So you guys any solution for my problem ?
Use this method to check the internet connection in the app:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Intent networkStateIntent = new Intent(Constants.NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(Constants.IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
public boolean isConnectedToInternet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
Register the reciever in the manifest file like this:
<receiver android:name=".utils.NetwrokConnection.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
use this method in the activity where you want to check the connection:
public void networkConnection() {
IntentFilter intentFilter = new IntentFilter(Constants.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(Constants.IS_NETWORK_AVAILABLE, false);
Dialogs.getInstance().showSnackbar(activity,(View) rootlayout, isNetworkAvailable);
}
}, intentFilter);
}
Also add the permission in the menifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Related
Before Android 7 we could define a broadcast receiver as below to get the notified about the changes in the network including mobile data.
<receiver android:name=".reciever.DataStateChangedReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
But as of Android 7, OS does not execute this broadcast receiver anymore as it's deprecated. I'm looking for a similar solution to achieve the same thing on Android 7 (figure out when mobile data state changes). Also, I'm aware that I can do this with dynamically registring broadcast in my Activity but That's not going to work for me because my app may be closed.
I'm looking for a solution to wake up my app whenever connectivity changes.
Using a service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver,intentFilter);
return START_STICKY;
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
notifyMobileNetworkChange(context);
}
else {
notifyWifiNetworkChange(context);
}
}
....
}
Wake up app:
private void notifyMobileNetworkChange(Context context) {
//Run anything you want here
Intent dialogIntent = new Intent(this, WiFiName.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
In Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can find the complete project here:
https://github.com/stupidly-logical/WiFiName
You can modify the same for Mobile Data
I have a printer inspection app on android phone, its basic inspection form
Inspector can work on a printer inspection even if he has no internet connection,
Once the phone is back with reception/internet, I would like to submit the inspection.
I was thinking to design the app using an android service
so it will save the inspection details using sqlite, then when there is internet connection to resubmit the inspection .
But this require service to periodically check for internet. and will consume significant battery juice.
Is there a hook I can register for my app to notify the app or the service on internet connection?
Simple check for both Wi-fi and Mobile internet as follows...
in Manifest.xml :
<receiver android:name=".com.yourapp.ConnectivityChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
make a new BroadcastReceiver :
public class ConnectivityChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context))
{
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
and finally ServiceManager class :
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
** Don't forget to add permission to use the Internet in your manifest file :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Also check out this super cool article on vogella.com AndroidServices ...
This is manifest part
<receiver
android:name="my.com.app.ConnectivityModifiedReceiver"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
This is java code
public class my.com.app.ConnectivityModifiedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("ConnectivityModified"));
}
}
The ConnectivityModifiedReceiver will send intents according to network connectivity change.In my case VPN connection and disconnection.
I am getting intents in Lollipop But not in JellyBean.
Plz help
So far in my findings
In Lollipop
android.net.conn.CONNECTIVITY_CHANGE broadcast is fired Only when either VPN is connected or disconnected.
So you can use the following code snippet along with the logic you have for pre-lollipop devices.
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String KeyNI="networkInfo";
android.net.NetworkInfo bundleNetworkInfo=(android.net.NetworkInfo)bundle.get(KeyNI);
if(!bundleNetworkInfo.getTypeName().toString().equalsIgnoreCase("VPN"))
{
context.sendBroadcast(new Intent("ConnectivityModified"));
}
}
Hope this helps.
You might give this a try on your onReceive if it helps:
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
// should check null because in air plan mode it will be null
if (netInfo != null && netInfo.isConnected()) {
System.out.println("INTERNET IS AVAILABLE");
} else {
System.out.println("INTERNET UNAVAILABLE");
}
}
You can place your logic inside the if statement.
Why on receive called twice, when Network state changed.
Manifest:
<receiver android:name="tv.meterreading.network.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" >
</action>
</intent-filter>
</receiver>
Receiving multiple broadcast is a device specific problem. Some phones just send one broadcast while other send 2 or 3. But there is a work around:
Assuming you get the disconnect message when the wifi is disconnected, I would guess the first one is the correct one and the other 2 are just echoes for some reason.
To know that the message has been called, you could have a static boolean that gets toggled between connect and disconnect and only call your sub-routines when you receive a connection and the boolean is true. Something like:
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;
}
}
}
How can I open my application when an user enters a zone that has wi-fi? Is this possible? Suppose my application is onPause() state (means My Device's homescreen). now when device connected with wifi. it will automatically open my application.
Try add broadcast receiver and listen network changes, when wi-fi connected start your activity. Something like this solution
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (((null != wifi)&&(wifi.isAvailable())) || ((null != mobile)&&(mobile.isAvailable()))){
Intent uplIntent = new Intent(context, YourActivity.class);
uplIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(uplIntent);
}
}
}
And add to manifest
<receiver android:name=".receiver.ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
What I can imagine is an overwriting of the onPause() Method like this:
#Override
public void onPause() {
String conn_context = Context.WIFI_SERVICE;
final WifiManager wifi = (WifiManager) getSystemService(conn_context);
if (wifi.isWifiEnabled())
{
super.onResume();
}
else
{
super.onPause();
}
}
But you must also figure a way to handle the real onPause event.
Maybe doable with the Tasker app from Play Store (not free though). Or you can create a Service (http://developer.android.com/guide/components/services.html) that will have code outlined in the other answers and then launch your app (Activity) when wifi is available.