I am using Volley for webcalls in my application and everything is working fine and smooth except one state in which somehow my device is not getting Network Connection but checking connection via code is returning true using below code.
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = SessionApplication.getConnectivityManager();
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
Instead of returning network state false using above code My volley web calls returning me this exception "handle com.android.volley.NoConnectionError: java.net.UnknownHostException".
I checked my internet connection by opening browser in my device and found it is also not working. So i am okay with application behavior but still i need to handle such condition because this is not user friendly user should be prompted a dialog that "Check Your Internet Connection!".
This should be a common issues in Android could any body please help me to give me best approach to handle such cases. Thanks in advance.
Network state is :
This exception indicates the problem in connectivity. In fact you can show some dialog about the connectivity. Overriding the onErrorResponse(VolleyError error) you can do like this -
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
if (error instanceof NoConnectionError)
new AlertDialog.Builder(this).setMessage(
"Unable to connect to the server! Please ensure your internet is working!").show();
}
Try this method might help
public boolean isConnectedToInternet(){
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null){
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null){
for (int i = 0; i < info.length; i++){
if (info[i].getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
}
}
return false;
}
Related
This question might be a duplicate question, but i cant find proper solution.
I have chat app in which i set function for when remote android device on background mode it will get notification by FCM when new message will come(new node added in chatroom).
So
if remote device is in the foreground mode than it will get notification by app and its has definitely internet connectivity for this i can set message delivery successfully.
if remote device is in the background mode than it will get notification by FCM and its has definitely internet connectivity. for this i can also set message delivery successfully.
So how do i check that remote device is totally offline(no internet connection) or how to check FCM is not success to send notification ?
for example:
if(messegeReceiver(remote device) has no internet connectivity )
{
//here i want to change data in firebase//
}
else
{
//here i want to change data in firebase//
}
I have "Users" node in which every users set device_token while login the app.
You can device checking offline/online mode via set one param in your chat table. When user exit or minimize application then set states to 0 and maximum set to 1.Best way if possible you use firebase real-time database for online offline.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
regisenter code hereterReceiver(receiver, filter);
public static class NetworkChangeReceiver extends BroadcastReceiver {
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public static 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) {
relativelayout_connection.setVisibility(View.GONE);
isConnected = true;
return true;
}
} else {
relativelayout_connection.setVisibility(View.VISIBLE);
}
}
}
} else {
relativelayout_connection.setVisibility(View.GONE);
isConnected = false;
return false;
}
return isConnected;
}
#Override
public void onReceive(final Context context, final Intent intent) {
// isNetworkAvailable(context);
if (isOnline(context)) {
} else {
relativelayout_connection.setVisibility(View.VISIBLE);
}
}
}
FCM does not guarantee that the push notification gets delivered. It completely depends upon various factors like internet connection (as you mentioned), OEM behavior, Doze mode etc.
In your case, you are trying to send messages via FCM from one device to another and shown messages in the form notifications just like any other chat application.
The only problem here is that the FCM does not provide you with delivery parameters in response (image attached) that you are looking for. It only gives count for number of notifications that has been accepted by the gateway i.e. FCM (success) and the count for number of notifications that has been rejected by the gateway (failure). It also gives the reason for rejection (error) message like NotRegistered, MissingRegistrationToken, etc and you can refer this for the same.
My suggestion here would be to have a handshake message in place that acknowledges the delivery of the push notification from the other device. As soon as you receive the push notification send a handshake message via FCM and that gets received by the first device which understands that the push notification has been delivered. In case if the device does not receive the handshake you assume that the message is yet to be delivered.
I hope this really helps you and please up vote the answer or accept the answer if you feel like doing so.
I am writing an android application which interacts with a sensor using bluetooth and obtains temperature values. I am doing this by calling connectGatt() which is asynchronous and calls a callback once the connection is established. The problem I am facing is that my code has to wait until the connection gets established.
This is the implementation of the method which is being used in the code below.
public boolean connect(final String address)
{
Log.v(LOG_TAG,"IN CONNECT METHOD"+Thread.currentThread().getName());
if(btadapter == null || address == null)
{
Log.v(LOG_TAG,"Unable to get Bluetooth Adapter or Address is not valid");
return false;
}
if(address != null && address.equals(btaddress) && btgatt != null)
{
Log.v(LOG_TAG,"Trying to connect to a bt gatt profile directly");
boolean result = btgatt.connect();
if(result)
return true;
return false;
}
btdevice = btadapter.getRemoteDevice(address);
if(btdevice == null)
{
Log.v(LOG_TAG,"Could not find device.");
return false;
}
btgatt = btdevice.connectGatt(this,false,btgattcallback);
Log.v(LOG_TAG,btgatt.toString());
btaddress = address;
Log.v(LOG_TAG,"Connecting to the device");
btConnectionState = STATE_CONNECTING;
return true;
}
Currently I could solve this problem by writing the following code in a handler thread as I don't want to block the UI thread while waiting for the callback. But I am not convinced with the approach.
if(mLocation != null)
{
connect(btaddress); // Method encapsulates calls to connectGatt method.
while (btConnectionState != STATE_CONNECTED) {
continue;
}
while (!services_discovered) {
continue;
}
//Other Code
I feel that there could be better ways of solving this but couldn't find any on the web. I saw a couple of answers using CountDownLatch and Semaphores but I didn't understand them clearly.
Can anyone help me with understanding how to handle situations like these?
Thank you.
I would like to know if on android it is possible to get a broadcast once the user clicks the wifi disconnect button to run a method BEFORE the device disconnects from the internet , I am already using a broadcast receiver to catch network change but it is executed after internet is disconnected I am using the code below :
public class InternetReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if (isNetworkAvailable(context) && !isMyServiceRunning(MessagingService.class,context)){
Intent i = new Intent(context,MessagingService.class);
context.startService(i);
Log.e("service started ","true");
}
}
private boolean isMyServiceRunning(Class<?> serviceClass, Context c) {
ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public boolean isNetworkAvailable(Context c) {
ConnectivityManager connectivityManager
= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
I am using the code above to run the service once internet is connected but it is just an example
Edit: I assume that you want to react to the user's click on the wifi disconnect button
You could check the state of the wifi connection by using Android's WifiManager which offers some possibilities to get information about your wifi environment and connection.
Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
Source: http://developer.android.com/reference/android/net/wifi/WifiManager.html
Have a look at the following. I guess it'll be helpful to you.
WIFI_STATE_CHANGED_ACTION Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
int WIFI_STATE_DISABLED Wi-Fi is disabled.
int WIFI_STATE_DISABLING Wi-Fi is currently being disabled.
I have read that the "ConnectivityManager" class gives information about the network. But I am confused on how to implement the code. I need an efficient way to check internet, wifi and GPRS at a time.
Thanks
And again: http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
You have to do something, nobody will write complete code for you. Read the documentation and you know when the event is fired and which you have to sort out.
Simply use this function. call this function where you want to check that internet is available or not.
public boolean isNetworkConnected(Context mContext) {
final String DEBUG_TAG = "NetworkStatusExample";
ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(CONNECTIVITY_SERVICE);
boolean isWifiConn=false;
boolean isMobileConn=false;
Network nn=connMgr.getActiveNetwork();
Network[] networkinf=connMgr.getAllNetworks();
for (int a=0;a<networkinf.length;a++) {
NetworkCapabilities networkCapabilities = connMgr.getNetworkCapabilities(networkinf[a]);
if (networkCapabilities.hasTransport(networkCapabilities.TRANSPORT_CELLULAR)){
isMobileConn=true;
}
else if (networkCapabilities.hasTransport(networkCapabilities.TRANSPORT_WIFI)){
isWifiConn=true;
}
}
Log.i(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.i(DEBUG_TAG, "Mobile connected: " + isMobileConn);
editor.putBoolean("isConnected",isMobileConn);
editor.apply();
if (isMobileConn || isWifiConn){
Log.i(DEBUG_TAG, "Network Status..." + isMobileConn);
return true;
}
else {
return false;
}
}
i would like to ask:
I have in my AppHelper class following method which check availability of internet connection.
public boolean checkInternetConnection(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Internet Connection Not Present");
return false;
}
}
Im trying to get Boolean value by using:
// check internet connection and availability
Boolean isConnectionAvailable = appHelper.checkInternetConnection(getBaseContext());
But unfortunately i get always null pointer exception. Is it matter of passed application context? And how should i solve that issue?
Thanks for any advice.
I'm going to take a stab in the dark and say that AppHelper class is a seperate Activity that is never properly started with an intent.
If this is so, I would instead implement AppHelper as a Service instead of an Activity, as the method "checkInternetConnection" is better suited for this type of task.
Weather or not the service runs in its own process or not I suppose would depend on the particular problem at hand.