Not receiving GCM notification on Android 6.0.1 [duplicate] - android

While working on a little project that integrates with GCM, I've stumbled across a bit of a strange issue.
Some times when I start watching the log to see if messages are received, messages do not appear to be coming through until I have changed the network state (I.E. originally on WiFi, if I turn off WiFi and move to Mobile Data, the messages arrive fine). After I've changed the network state, messages start to arrive perfectly fine, and the same applies once I change the network state back to what it was before (in this case, WiFi) the messages continue to be received.
The project itself includes the ability to start on boot (starts the GCMBaseIntentService on boot), which again works perfectly fine, and I'm sure the app / service is running as I've manually started up the app when this issue occurs (which also checks to see if the service is running, and if it's not it runs it and checks to see if it's registered).
Has anyone else come across this issue, or has any pointers as to how I could resolve this? I'm not seeing anything of much help in the log between the time messages are not being received and when they are (after changing the network state). I've gone through the GCM docs and can't see any mention of messages not being received due to a time-out (on the device itself), or any config options that might affect this.
Appreciate any assistance - I can provide source if needs be, although it hardly deviates from the demo app provided in the android-sdk.

I've noticed this as well. Although I haven't dug into the actual code, here's my understanding of why this happens.
GCM (and most push messaging services) works by keeping a long-lived socket open to Google's push notification server. The socket is kept open by sending "heartbeat" messages between the phone and server.
Occasionally, the network state may change and this socket will be broken (because the IP address of the device changes, from 3g to wifi, for example). If the message comes in before the socket is reestablished, then the device will not immediately get the message.
The reconnection only happens when the phone notices the socket is broken, which only happens when it tries to send a heartbeat message.
Again, just my basic understanding of how it works and why it happens, and I could be wrong.

There are many causes for GCM message delays. If message start to arrive after you changed network state, or switched on/off airplane mode - the most likely cause is a network that closes the connection without sending FIN/RST.
GCM maintains a long-lived connection - and reconnects if it knows the connection was broken.
A router/AP/NAT is supposed to send a FIN or RST to terminate the TCP connection - so GCM and servers will know the connection is dead.
However a number of routers and mobile operators don't do this, and then GCM needs to rely on the heartbeat, ~15 min on Wifi, more on mobile. There is a trade-off between battery life/network use and heartbeat frequency.

As per your comment in above answer and according to my experience with GCM push notifications there isn't any reason that if network(internet connection) is available you should not receive push notifications I always check internet connection availability before running the application for push notification like this try checking this if this is true you should receive push notifications
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}

so, If #theelfismike thinking is true, may I use something like:
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
// here the network changed to Wifi so I can send a heartbeat to GCM to keep connection
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
//here the network changed to mobileData so I can send a heartbeat to GCM to keep connection
}
is my solution good?

in the GCMIntentSevice class ,when you receive message from server ,onMessage method gets called so at that time you can do something like...
PowerManager pm = (PowerManager) getApplicationContext()
.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(
(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),"TAG");
wakeLock.acquire();
and you have to add
<uses-permission android:name="android.permission.WAKE_LOCK" />
permission in you manifest file..
this should do the trick...

Related

How to check if a device is under Connecting state when connecting to wifi or mobile data?

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.

how to convert network state from blocked to connected

I am trying to establish tcp socket connection when my app is in background, before I start connect to server, I checked the network state with the code below
ConnectivityManager connectivityManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
NetworkInfo.DetailedState state = info.getDetailedState();
and find the state is BLOCKED, which will cause failure for the tcp connection.
I was wondering is there any method to change network state from Blocked to Connected state? Any advice is appreciated, thanks in advance.
PS: I am working on MIUI rom, other roms may not have this issue.
You can't simply force a change of state. This state indicates that the device is simply not allowed to use the network, even though it might be connected. The BLOCKED state typically means that the user of the device has chosen to not allow background data access. (Maybe they have limited data on their plan and need to control access to data usage.)

Get WiFi captive portal info

Is there a way to access Android's broadcast that the WiFi connection is currently a captive portal (requires web login)? Android seems to do have this built in. If not a broadcast receiver, is there a way to check for the result of the captive portal check? I believe it's using this class, which is hidden from the API:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.L_preview/android/net/CaptivePortalTracker.java
Prior to 4.2, it was probably using:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.2_r1/android/net/wifi/WifiWatchdogStateMachine.java
Background:
I had been using my own method to detect whether WiFi likely required a login. I would wait for a WiFi connected state, then ping a site and make sure there was a response. This seemed to work great in most cases. Another strategy is to do a HttpRequest and check for a redirect or the response body you receive back, similar to Android's strategy in the classes listed above.
However, new to Lollipop is that the mobile data connection is used when WiFi does not have connectivity. This means my ping method will still return results, and that a redirect would not happen, as the request would be routed over the mobile data.
Is there a way to get Android's current status of a WiFi captive portal? If not, can we make sure a request goes over WiFi even when there's no connectivity as seen by Android?
You'd have to use the new ConnectivityManager.setProcessDefaultNetwork API to force your app to communicate over the captive portal. See https://github.com/pawitp/muwifi-autologin/commit/f045fe36f1fd98a106ea652e2d56f7ddfc871760 for an example.
Complete code added:
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
for (Network net : cm.getAllNetworks()) {
if (cm.getNetworkInfo(net).getType() == ConnectivityManager.TYPE_WIFI) {
Utils.logDebug(TAG, "Seting process network to " + net);
/*Since API 23 ConnectivityManager.setProcessDefaultNetwork(net);
is deprecated, use: */
cm.bindProcessToNetwork(net);
}
}

Google Cloud Messaging - messages sometimes not received until network state changed

While working on a little project that integrates with GCM, I've stumbled across a bit of a strange issue.
Some times when I start watching the log to see if messages are received, messages do not appear to be coming through until I have changed the network state (I.E. originally on WiFi, if I turn off WiFi and move to Mobile Data, the messages arrive fine). After I've changed the network state, messages start to arrive perfectly fine, and the same applies once I change the network state back to what it was before (in this case, WiFi) the messages continue to be received.
The project itself includes the ability to start on boot (starts the GCMBaseIntentService on boot), which again works perfectly fine, and I'm sure the app / service is running as I've manually started up the app when this issue occurs (which also checks to see if the service is running, and if it's not it runs it and checks to see if it's registered).
Has anyone else come across this issue, or has any pointers as to how I could resolve this? I'm not seeing anything of much help in the log between the time messages are not being received and when they are (after changing the network state). I've gone through the GCM docs and can't see any mention of messages not being received due to a time-out (on the device itself), or any config options that might affect this.
Appreciate any assistance - I can provide source if needs be, although it hardly deviates from the demo app provided in the android-sdk.
I've noticed this as well. Although I haven't dug into the actual code, here's my understanding of why this happens.
GCM (and most push messaging services) works by keeping a long-lived socket open to Google's push notification server. The socket is kept open by sending "heartbeat" messages between the phone and server.
Occasionally, the network state may change and this socket will be broken (because the IP address of the device changes, from 3g to wifi, for example). If the message comes in before the socket is reestablished, then the device will not immediately get the message.
The reconnection only happens when the phone notices the socket is broken, which only happens when it tries to send a heartbeat message.
Again, just my basic understanding of how it works and why it happens, and I could be wrong.
There are many causes for GCM message delays. If message start to arrive after you changed network state, or switched on/off airplane mode - the most likely cause is a network that closes the connection without sending FIN/RST.
GCM maintains a long-lived connection - and reconnects if it knows the connection was broken.
A router/AP/NAT is supposed to send a FIN or RST to terminate the TCP connection - so GCM and servers will know the connection is dead.
However a number of routers and mobile operators don't do this, and then GCM needs to rely on the heartbeat, ~15 min on Wifi, more on mobile. There is a trade-off between battery life/network use and heartbeat frequency.
As per your comment in above answer and according to my experience with GCM push notifications there isn't any reason that if network(internet connection) is available you should not receive push notifications I always check internet connection availability before running the application for push notification like this try checking this if this is true you should receive push notifications
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
so, If #theelfismike thinking is true, may I use something like:
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
// here the network changed to Wifi so I can send a heartbeat to GCM to keep connection
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
//here the network changed to mobileData so I can send a heartbeat to GCM to keep connection
}
is my solution good?
in the GCMIntentSevice class ,when you receive message from server ,onMessage method gets called so at that time you can do something like...
PowerManager pm = (PowerManager) getApplicationContext()
.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(
(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),"TAG");
wakeLock.acquire();
and you have to add
<uses-permission android:name="android.permission.WAKE_LOCK" />
permission in you manifest file..
this should do the trick...

Android Internet Connection Broadcast Recevier

My app is running in the background (as a Service) and needs to be connected to a remote server all the time to receive and send messages.
This Service runs a Thread which manage the connection to the server (with Socket)
i'm trying to write an internet connection Broadcast Receiver which will run every time the internet state is changed and check if the state is connected of disconnected.
my problem is as follow: when i'm connected to Wi-Fi network the Broadcast Receiver Intent is fired few times which in all of them the state of the internet connection is true (with no disconnection between every fire, which means i have few new Threads using the Socket to connect the server.
How can i make sure i'm getting the state of the internet right, and by right i mean that the .isConnected() method will return if and only if the connection is connected ?
this is my code:
public void onReceive(Context context, Intent intent)
{
action = intent.getAction();
app = (AppVariables) context.getApplicationContext();
if (app.isApplicationInitilized())
{
if (action.equals(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)))
{
networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected())
app.getServerConnectionManager().startServer();
}
else if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
{
networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected())
app.getServerConnectionManager().stopServer(false);
else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE && !networkInfo.isConnected())
app.getServerConnectionManager().stopServer(false);
else
app.getServerConnectionManager().startServer();
}
}
}
I've had the same issue for one of my apps, and the pattern we deployed (successfully) is as follows:
onReceive():
if( networkInfo.isConnected() )
fireTimerForSecondaryCheck();
else
not connected;
SecondaryCheck:
if( loadKnownUrl() )
is connected.
fire long timer for secondary check
else
fire short timer for secondary check
Basically what this does is attempt to access the internet once the network manager reports that wifi is up. If it receives the expected content, then the network connection is up and working, and I'll check again in two minutes. If I don't receive the expected content, it means either the network connection is not fully up, can't connect to the internet, or the wifi might have a landing page for TOS or similar. In that case, I check again in 10 seconds.
FWIW, my NetworkMonitorService broadcasts connectivity to my app, which registers for it, and updates the UI as necessary.
This was developed in 2.3.3, and I believe the newer Android versions (4+) have finer granularity in the network state, but I haven't seen the need to adjust this code yet in production. It works well from 2.2 devices all the way to 4.2.
If I understand correctly you need to know the state of connection.
You can obtain that by using networkInfo state:
State state = networkInfo.getState();
if (state == State.CONNECTED) do_something

Categories

Resources