I'm am developing an Android app that uses Volley to send some data entered by the user to my server. I am also saving this data in a local SQLite database. All this works just fine. The problem occours if the internet connection is lost. How do I know when I must try to re-upload the data.
If the network connection is lost I can use a BroadcastReceiver to find out when the connection is established. However how do I ensure this works even when the device is connected to the network but there is no access to the internet.
Try this way
1.Check your Internet Connection before you want to upload data to some View (Ex.ListView)
If Available, upload server data.
else
upload local/saved data.
This may helps you
Create a broadcast receiver to listen to the internet changes and register it:
class NetworkStateBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo.isConnected()){
//netwok just connected, upload
}
}
Create an instance and register it.(may be in application class, which runs throughout your app)
reciever = new NetworkStateBroadcastReceiver();
registerReceiver(mReciever, new intentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
Related
I am developing the android app which runs my web service at app startup. My app is basically the home app of the device. So that's mean that When user will reboot the device, My app will come in front of him.
So far that is great. But I have noticed it that on app start the device takes 5 to 10 seconds to get the internet connected. whereas my web service gets run before the internet is established thus throwing an error of "An error occurred please try again later."
What I Want: Though I am showing that message I am really not satisfied as I really do want to show the user a Message. That message should be "Device is connecting to the internet"
but unfortunately, I am unable to do so. I am using the following code
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
but it really indicates me if the net is connected or not.
So is not there the case where I can show a message like "Please wait device is connecting to the internet"
Or how can I get that device is restarted not the only app. ... Please help
Register a local (or Manifest-declared if you want) broadcast receiver in your activity (documentation here https://developer.android.com/guide/components/broadcasts), listening to connectivity changes, using this intent filter: IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).
Then check if is the device has internet connection with the code you posted.
Remember to register your broadcast receiver inside onResume() method and to unregister it inside onPause() method
From api 24 and above:
you can use registerDefaultNetworkCallback https://developer.android.com/reference/android/net/ConnectivityManager.html#registerDefaultNetworkCallback(android.net.ConnectivityManager.NetworkCallback)
The callback has a public method called "onAvailable" https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback.html#onAvailable(android.net.Network) that is called when a new network is ready to be used.
I am trying to connect to a WiFi network using WiFiManager. Here is the code I use to do so :
WifiManager manager = [...];
WifiConfiguration config = new WifiConfiguration();
manager.setWifiEnabled(true);
//Set SSID, PSK, etc...
[...]
//Connect to the network
int netId = manager.addNetwork(config);
if (netId == -1)
{
Toast.makeText(this, "Invalid PSK", Toast.LENGTH_LONG).show();
return;
}
manager.enableNetwork(netId, true);
manager.saveConfiguration();
Beforehand, I registered a BroadcastReceiver for the WifiManager.NETWORK_STATE_CHANGED_ACTION action. I'm trying to detect when the connection succeeds or fails (for various reasons including authentication) by checking the DetailedState of the given NetworkInfo.
Everything works when the connection succeeds, but for some reason my receiver isn't "executed" when the connection fails. The network is added to the device's list, I can see it by going into WiFi Settings, but it does not try to connect (or it does try to connect but doesn't notify my receiver).
Any clue ? Thanks !
I finally managed to achieve what I wanted.
To detect that the connection succeeded, register the WifiManager.NETWORK_STATE_CHANGED_ACTION broadcast intent and check for the NetworkInfo.DetailedState.OBTAINING_IPADDR detailed state (for WiFi obviously).
To detect that the connection failed, register the WifiManager.SUPPLICANT_STATE_CHANGED_ACTION broadcast intent and check for any WifiManager.EXTRA_SUPPLICANT_ERROR integer extra (typically WifiManager.ERROR_AUTHENTICATING). You may need to gain access for Android hidden API to achieve that.
The enableNetwork method return true if the connection status is success.
This works fine on success but is not the best method to check the failed status (return true if the connection failed after the first step authentication).
I think that you can check in the networkInfo object the actual connected network to see if the request is ok:
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
I want to create a method which tells if the device is online. As far as I understand ConnectivityManager tells only if the device is connected to a network. This doesn't mean that the device is connected to the internet. To ensure that the device is online I'm using InetAddress.getByName("google.com").isReachable(3); but I can't use it on the main thread. I can create a separate thread to check the connectivity and then use a callback function but is there another way? I don't want my app to do anything before it is connected. Do you have any solutions? Thank you!
With any networking, there isn't a guaranteed way to check whether or not you are connected to an endpoint without actually sending data. Even if the device is connected to a network, has an ip address, recently received data, e.t.c, it doesn't mean that you still have a connection.
I would suggest allowing the user to progress into your application as much as possible, queuing up the requests to your server in the background whilst a connection is established. Use the same framework to resend data if the connection is lost whilst the user is using the app. Make the connection to the server as transparent to the user as possible, unless it fails to connect after ~1 minute
try this:
public static 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;
}
I'm working on an app that logins on a public wifi network. I've got the login working by doing a http post to the authentication server.
My next step is making the app do the http post automatically when there's a new wifi connection, checking that we are connected to the correct ssid.
My question is, which is the best way of doing this? Is the best way to create a service and registering to a broadcastreceiver?
Thanks for your help
The way I do it is that i have a broadcastreceiver that listens to android.net.conn.CONNECTIVITY_CHANGE intents. In that broadcast receiver you can check what kind of connection is made by polling the ConnectivityManager:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean hasWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isAvailable() && cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
And then start the service doing the post to the auth server.
Alternatively you could indeed let the service listen to android.net.conn.CONNECTIVITY_CHANGE intents and do the wifi check there.
I have an AlarmManager which sets a repeating alarm. (Not actually an alarm, but send mail). So in the BroadcastReceiver I do the actual sending of the mail. But to send mail one needs Internet. So when the phone doesn't have an Internet connection the email doesn't get sent. How do I "snooze" the action which is inside onReceive() in my BroadcastReceiver? Do I make a new Receiver which fires with this (when phon haz internietz) or???
private boolean isNetworkAvailable() {
ConnectivityManager cm
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ai= cm.getActiveNetworkInfo();
return ai!= null;
}
EDIT:
Got it to work. Used a IntentService which checks every 10 minutes if internet is avaliable, and if: send mail. The IntentService is started from my BroadcastReceiver, where the email initially is to be sent, if there's no internet.
Just Use Background Service Which Checks The Internet Connection.
if Internet available it just send the Email unless start your service which checks the internet connection in every minute until the email send and after that close your service.