How to detect device status Offline/Online in Android - android

I am noob in Android. I want to display device status at web dashboard whether device is offline/online. Is GCM helpful for this to do or something what should I use for this .
Or Should I call any Web API continuous to send the phone status from phone to server until phone is ON so that I can display here "Online" status of phone at web dashboard ??
Offline status when your device is OFF & Online status when your device is ON
Any idea ??

Step 1 -> Register for the Broadcast Receiver to check for device status offline/online.
Inside the onReceive() method of the Broadcast Receiver, check for network changes, if there is a change go to step 2.
Step 2 -> Get the device status and call the web api along with the POST parameter "device_status".
Use the below API to get status for Internet Connectivity.
public boolean testNetwork(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected())
|| (connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null &&
connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnected())) {
return true;
} else {
return false;
}
}
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean connectivity = CommonUtils.getInstance().testNetwork(
BaseActivity.this);
if (!connectivity) {
// write your code
} else {
//write your code
}
}
};
IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
try {
registerReceiver(networkStateReceiver, filter);
} catch (Exception e) {
e.printStackTrace();
}

use this method :
You should not send ping to server.Server should send ping after some time interval to the device and device should reply. If device is not replying this means user is offline. Basically you need to create socket connection with server and exchange ping
same thing is implemented on openfire server

public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
/*
* Toast.makeText(getActivity(), "No Internet connection!",
* Toast.LENGTH_LONG).show();
*/
return false;
}
return true;
}
and call it like
if (isOnline()) {
//code if online
} else {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
alertDialog.setTitle("Info");
alertDialog
.setMessage("Internet Not Available, Cross Check Your Internet Connectivity and Try Again!");
alertDialog.show();
}

Implement XMPP Protocol along with any Jabber server.
It gives you correct info because it was created to make the offline/ online system
for help use link below
https://xmpp.org/about/

Related

Android network state change detection takes time

I am trying to detect network state change in my android app. I followed the answer in that question : Check INTENT internet connection
This works, but it takes time for broadcastreceiver to detect changes. When i turn wifi on or off, about 10 seconds later the onReceive() method is called. Why is that taking so much time? Can anyone help?
Thanks
Here is my code:
public class NetworkStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("app", "Network connectivity change");
if (intent.getExtras() != null) {
NetworkInfo ni = (NetworkInfo) intent.getExtras().get(
ConnectivityManager.EXTRA_NETWORK_INFO);
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
Log.i("app", "Network " + ni.getTypeName() + " connected");
Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
} else if (intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_LONG).show();
Log.d("app", "There's no network connectivity");
}
}
}
}
and in my Manifest's application tag:
<receiver android:name="com.mypackage.NetworkStateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
I found the solution.
Instead of extending BroadcastReceiver class and creating NetworkStateChangeReceiver, i created a broadcastreceiver on my activity and registered it there. Now it works and onReceive() method is triggered immediately.
public static boolean isInternetAvailable(Context context) {
boolean isConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (int index = 0; index < info.length; index++) {
if (info[index].getState() == NetworkInfo.State.CONNECTED) {
isConnection = true;
break;
}
}
}
}
return isConnection;
}
I have similar code within my app to detect if there's a connection present, and prompt the user of connection state changes.
Within my application, it receives the connection change for disconnect within a second, however when you go to turn the WiFi on it takes around ~7 seconds before my app receives the change in connection state.
However I receive the state change exactly the same time Android makes the toast saying "Connected to Wi-Fi network [your network name]".
Chances are you'd be receiving the change simultaneously from when it connects to a network, and not from when you pushed the Wi-Fi toggle to turn it on.
Is there a particular reason you need that instant feedback from when the toggle is pressed?

Using Broadcastreceiver to get network state change

This is my first time using broadcast-receivers, and i thought it would be a little more straight forward than this. I have a class looking like this:
public class NetworkChangeReceiver 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);
boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() || mobile != null && mobile.isConnectedOrConnecting();
if (isConnected) {
Log.d("Network Available ", "YES" + getResultCode());
}else{
Log.d("Network Available ", "NO" + getResultCode());
}
}
}
and i've registered it in my application like this
mReceiver = new NetworkChangeReceiver();
registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
And this is working OK, when i shut off my wifi, i get "NO" in log.d.. But how do i get something to "happen"? I want a Return-value or something which i can work with, for example if isConnected is false, then restart activity or something.
I've googled for days trying to understand what they are and how they work... Please help!
Well, the method is of type void, so a return value is out of the question. And besides, the calling class would be BroadcastManager or LocalBroadcastManager, so you wouldn't have any access to a potential return value.
You could register custom listeners inside your BroadcastReceiver, but that would mean keeping unnecessary references.
What I would do in your situation is fire off another broadcast with a custom "action" String in the "NO" block:
else{
Log.d("Network Available ", "NO" + getResultCode());
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(YOUR_CUSTOM_ACTION_NAME));
}
Register a listener for that event wherever needed and handle the behavior there.

Android internet connectivity check

am trying to check for available internet connection, i find many subjects speaking about this, but i still have a problem when i try to verify for the internet connection, the code am using is the flowing:
public boolean isOnline() {
ConnectivityManager conMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
How can help me please ?
PS: Sorry for my bad English.
Your method is correct. Also you'll need in your android manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But keep in mind that low signal, server downtime, captive portals, content filters, other network problems can prevent your application from reaching a server. So having an active network interface doesn't guarantee that a particular networked service is available.
In this code you have red status in private var:
private boolean mIsConnected;
#Override
protected void onResume()
{
super.onResume();
//red status broadcast
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
}
private BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo networkInfo =
(NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
mIsConnected= networkInfo.isConnected();
Log.i("TAG", String.format("Status red: %b", mIsConnected))
}
};

CONNECTIVITY_ACTION intent received twice when Wifi connected

In my app I have a BroadcastReceiver that is launched as a component through a <receiver> tag, filtering android.net.conn.CONNECTIVITY_CHANGE intents.
My goal is simply to know when a Wifi connection was established, so what I am doing in onReceive() is this:
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
// Wifi is connected
}
It works fine, but I always seem to get two identical intents within about one second when a Wifi connection is established. I tried to look at any info I could get from the intent, the ConnectivityManager and WifiManager, but I can't find anything that distinguishes the two intents.
Looking at the log, there is at least one other BroadcastReceiver that also receives the two identical intents.
It is running on a HTC Desire with Android 2.2
Any idea why I seem to get a "duplicated" intent when Wifi connects or what the difference between the two might be?
NOTE: For a recent, up-to-date answer, see this one below!
After a lot of googling and debugging, I believe this is the correct way to determine if Wifi has connected or disconnected.
The onReceive() method in the BroadcastReceiver:
public void onReceive(final Context context, final Intent intent) {
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
// Wifi is connected
Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));
}
} else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
! networkInfo.isConnected()) {
// Wifi is disconnected
Log.d("Inetify", "Wifi is disconnected: " + String.valueOf(networkInfo));
}
}
}
Together with the following receiver element in AndroidManifest.xml
<receiver android:name="ConnectivityActionReceiver"
android:enabled="true" android:label="ConnectivityActionReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
Some explanation:
When only considering ConnectivityManager.CONNECTIVITY_ACTION, I always get two intents containing identical NetworkInfo instances (both getType() == TYPE_WIFI and isConnected() == true) when Wifi connects - the issue described in this question.
When only using WifiManager.NETWORK_STATE_CHANGED_ACTION, there is no intent broadcasted when Wifi disconnects, but two intents containing different NetworkInfo instances, allowing to determine one event when Wifi is connected.
NOTE: I've received one single crash report (NPE) where the intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO) returned null. So, even if it seems to be extremely rare to happen, it might be a good idea to add a null check.
Cheers,
Torsten
If you're listening on WifiManager.NETWORK_STATE_CHANGED_ACTION you'll receive this twice because there are 2 methods in the NetworkInfo
isConnectedOrConnecting()
isConnected()
First time isConnectedOrConnecting() returns true and isConnected() false
Second time isConnectedOrConnecting() and isConnected() return true
Cheers
This is the proper way to register for connectivity changes on API 21 and higher. The following code can be placed in a base activity and that way you can expect every screen in your app (that inherits from this activity) to get these callbacks.
First, create a network callback which will monitor connectivity changes.
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private val networkCallback: ConnectivityManager.NetworkCallback = object : ConnectivityManager.NetworkCallback() {
// Implement the callback methods that are relevant to the actions you want to take.
// I have implemented onAvailable for connecting and onLost for disconnecting.
override fun onAvailable(network: Network?) {
super.onAvailable(network)
}
override fun onLost(network: Network?) {
super.onLost(network)
}
}
Then, register and unregister this callback in the relevant spots.
override fun onResume() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
cm?.registerNetworkCallback(NetworkRequest.Builder().build(), networkCallback)
}
}
And unregister when appropriate.
override fun onPause() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
cm?.unregisterNetworkCallback(networkCallback)
}
}
Notice that there is a check for Build.VERSION_CODES.LOLLIPOP. This functionality is only available in Lollipop and above. Be sure to have a plan for how to handle network status changes in Pre-Lollipop devices if you support less than API 21 in your app.
Updated the code of Torsten, such that when WIFI gets disconnected, only the single appropriate broadcast is acted upon.
Used NetworkInfo.getDetailedState() == DetailedState.DISCONNECTED for the checking.
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// Wifi is connected
Log.d("Inetify","Wifi is connected: " + String.valueOf(networkInfo));
}
} else if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getDetailedState() == DetailedState.DISCONNECTED) {
// Wifi is disconnected
Log.d("Inetify","Wifi is disconnected: "+String.valueOf(networkInfo));
}
}
}
If you registered the activity as an intent listener then you will recieve the same message twice. Specifically, you need to choose whether you want to listen on the Package level (XML) or the programatic level.
If you set up a class for a broadcast reciever and attach the listen to it AND you attach an intent filter to the activity, then the message will be replicated twice.
I hope this solves your issue.
I solved twice call by using SharedPref with Time.
private static final Long SYNCTIME = 800L;
private static final String LASTTIMESYNC = "DATE";
SharedPreferences sharedPreferences;
private static final String TAG = "Connection";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Network connectivity change");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
if(System.currentTimeMillis()-sharedPreferences.getLong(LASTTIMESYNC, 0)>=SYNCTIME)
{
sharedPreferences.edit().putLong(LASTTIMESYNC, System.currentTimeMillis()).commit();
// Your code Here.
}
}
else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d(TAG, "There's no network connectivity");
}
}
Because there is small delay between 1.call and 2.call (About 200 milisec).
So in IF with time second call will stop and just first will continue.
I solved if with
in
onCreate()
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
ctx.registerReceiver(outgoingReceiver, intentFilter);
in
BroadcastReceiver
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
networkInfo.isConnected()) {
// Wifi is connected
Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));
Log.e("intent action", intent.getAction());
if (isNetworkConnected(context)){
Log.e("WiFi", "is Connected. Saving...");
try {
saveFilesToServer("/" + ctx.getString(R.string.app_name).replaceAll(" ", "_") + "/Temp.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
Log.e("NetworkInfo", "!=null");
try{
//For 3G check
boolean is3g = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
//For WiFi Check
boolean isWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnected();
Log.e("isWifi", "isWifi="+isWifi);
Log.e("is3g", "is3g="+is3g);
if (!isWifi)
{
return false;
}
else
{
return true;
}
}catch (Exception er){
return false;
}
} else{
Log.e("NetworkInfo", "==null");
return false;
}
}
I solved this problem by using the intent extra for NetworkInfo.
In the example below, onReceive event is fired only once if wifi is connected or mobile.
if (intent.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean screenIsOn = false;
// Prüfen ob Screen on ist
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
screenIsOn = pm.isInteractive();
} else {
screenIsOn = pm.isScreenOn();
}
if (Helper.isNetworkConnected(context)) {
if (networkInfo.isConnected() && networkInfo.isAvailable()) {
Log.v(logTAG + "onReceive", "connected");
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.v(logTAG + "onReceive", "mobile connected");
} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.v(logTAG + "onReceive", "wifi connected");
}
}
}
and my helper:
public static boolean isNetworkConnected(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null;
}
If you only want to receive it once, you can simply control it through variables.
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
NetworkInfo activeNetwork = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.isConnected() && !isUpdated) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
}
isUpdated = true;
} else {
isUpdated = false;
}
}
}
When turning WIFI ON,
With MOBILE data ON, two broadcasts are sent:
Broadcast #1 : MOBILE data disconnected, and
Broadcast #2 : WIFI connected
With MOBILE data OFF, only one broadcast is sent:
Broadcast #1 : WIFI connected
Similar behavior can be observed while turning the WIFI OFF under the above two conditions.
To distinguish between the two, please follow #2 and #3 below:
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "*** Action: " + intent.getParcelableExtra("networkInfo"));
NetworkInfo netInfo = intent.getParcelableExtra("networkInfo");
if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if (netInfo.getState().name().contains("DISCONNECTED")
&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d(TAG, "WIFI disconnect created this broadcast. MOBILE data ON."); // #1
} else if (netInfo.getState().name().contains("CONNECTED")
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "WIFI connect created this broadcast."); // #2
}
} else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
if (netInfo.getState().name().contains("DISCONNECTED")
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "MOBILE data disconnect created this broadcast. WIFI ON."); // #3
} else if (netInfo.getState().name().contains("CONNECTED")
&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d(TAG, "MOBILE data connect created this broadcast."); // #4
}
}
} else {
Log.d(TAG, "No network available");
}
}
}
The way I handled it, was simply by saving the state of the network and then comparing it to see if there was a change.
public class ConnectivityChangedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean previouslyConnected = MyApp.getInstance().isNetworkPreviouslyConnected();
boolean currentlyConnected = MyApp.getInstance().isNetworkConnected();
if (previouslyConnected != currentlyConnected) {
// do something and reset
MyApp.getInstance().resetNetworkPreviouslyConnected();
}
}
}
If this is the approach you take, it's important to reset it in onResume of your fragment or activity, so that it holds the current value:
#Override
public void onResume() {
super.onResume();
MyApp.getInstance().resetNetworkPreviouslyConnected();
}
I did that in my BaseFragment, a parent of all fragments in my app.
check networkType from intent
and compare activeNetworkInfo.getType()
Bundle bundle = intent.getExtras();
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
if(bundle.getInt("networkType") == ni.getType()) {
// active network intent
}
}
Found a special case for network connectivity saying there is no internet but actually there is. It turns out getActiveNetworkInfo will always return you DISCONNECTED/BLOCKED in a specific case when network is changed while battery level is low and app was just switched
Check out this post
Only listen to action "android.net.conn.CONNECTIVITY_CHANGE". It's broadcasted whenever connection is established or destroyed.
"android.net.wifi.STATE_CHANGE" will be broadcasted when connection established. So you get two triggers.
Enjoy!

ANDROID: if WiFi is enabled AND active, launch an intent

This is what I would like to do :
=> IF WiFi is enabled AND active, launch an intent (in fact it's a WebView that gets its content=>the instructions of my app on the web)
=> IF NOT, then I would launch another intent so that I don't show a WebView with "Web page not available ... The Web page at http://www.mywebsite.com might be temporarily down or it may have moved ..."
I tought initially to use
if(wifi.isWifiEnabled())
but that does not say if the Wifi connection is ACTIVE or not. It says only that the user has turned the switch on. The device may or may not be connected... Is this correct ?
Then I tried to use :
if (wifi.getConnectionInfo().getSSID()!= null)
but I noticed that it returns a string even if the connection has been lost or has been disabled ... ?
How should I do then ?
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
Intent intent_instructions;
if (wifi.getConnectionInfo().getSSID()!= null){
Log.i("Hub", "WiFi is enabled AND active !");
Log.i("Hub", "SSID = "+wifi.getConnectionInfo().getSSID());
intent_instructions = new Intent(this, Instructions.class);
}else{
Log.i("Hub", "NO WiFi");
intent_instructions = new Intent(this, Instructions_No_WiFi.class);
}
this.startActivity(intent_instructions);
Is there a more general way to test if the device has the connectivity to the internet just before launching an intent ? be it through Wifi, 3G, etc ...
Thanks in advance for your help.
You can use the following code to check for connectivity:
private static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return networkInfo == null ? false : networkInfo.isConnected();
}
Please make sure that you've registered the android.net.conn.CONNECTIVITY_CHANGE intent in your Manifest, or else, you'll never receive a notification that you're online.
I've been struggling with this issue for the last couple of days and I just now realized that I needed to register CONNECTIVITY_CHANGE and not only WIFI_STATE_CHANGED.
Try android.net.ConnectivityManager.getActiveNetworkInfo(): if it returns null you have no connection; if it returns a NetworkInfo object, you can check the connection's state with NetworkInfo.getState(), and if it's NetworkInfo.State.CONNECTED then you're connected, else you're not.
You can do it as follows:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)){
Log.d("WIFI", "WIFI has changed");
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
Log.d("WIFI", "WIFI State = " + wifiState);
setCurrentWifiState(wifiState);
}
You will get 0,1,2,3 depending on which state the Wifi is in, so for example 2 is connecting, you can check the rest in the documents
In your BroadcastReceiver class:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)){
boolean connected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
if (connected){
// start your service here
}
}
}
And in your AndroidManifest.xml make sure you register for the android.net.wifi.supplicant.CONNECTION_CHANGE broadcast intent.
<intent-filter >
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
</intent-filter>
isConnected() doesnt work fully ok, research something else
final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if( wifi.isAvailable() && wifi.getDetailedState() == DetailedState.CONNECTED){
Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
}
else if( mobile.isAvailable() && mobile.getDetailedState() == DetailedState.CONNECTED ){
Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
}
this code check if you are with wifi or 3g or nothing , in the case of wifi on but not connected to a net or 3g have signal problem it detect this details, with DetailedStates

Categories

Resources