How to verify if user has network access and show a pop-up alert when there isn't
You can simply use a function to check if you have network connection, by pinging Google servers:
/system/bin/ping -c 1 8.8.8.8
In Android, this function looks like this:
public boolean isNetworkAvailable() {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = process.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
In Firestore, offline persistence is enabled by default. So you can check if the user reads data from the cache or from Firebase servers. A more elegant way would be to use isFromCache()
function. This is the code for Android:
yourDocRef.addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
Log.d("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
}
});
Display an alert when internet connection not available in android application
public void onCreate(Bundle obj) {
super.onCreate(obj)
setContextView(layout);
if (isOnline()) {
//do whatever you want to do
} else {
try {
AlertDialog alertDialog = new AlertDialog.Builder(con).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
} catch (Exception e) {
Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
}
}
}
Check whether there is an Internet connection available on Flutter app
The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet
Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.
You can use
import 'dart:io';
...
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}
} on SocketException catch (_) {
print('not connected');
}
Update
The connectivity package is deprecated. Use the official Flutter Community connectivity_plus package instead.
Can you check for firebase server problems in android code?
In my app I already have a way of checking if the user has a problem with the internet connection
If your solution is similar to this one:
- How to verify if user has network access and show a pop-up alert when there isn't
Then you should go ahead with it.
But is there a way of knowing beforehand if the server itself is having problems (like an outage, downtime, etc.)
As in the above example, to know if you have an internet connection, you simply ping Google servers, which are unlikely to be down. Since Firebase servers are apart from Google, you can use that solution similarly.
If you want something more advanced, you can create an HTTP request, and check the status against your Firebase Project URL. To know the server response, handle the error by checking the error message for the status codes. Please see below a list of all available HTTP response status codes:
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
and not when I check for failed tasks in the onComplete callback.
If your onComplete is triggered, it means that Firebase servers accepted, or rejected your request, according to the state of the Task object. This can be successful or not. If it's not, it doesn't mean that the Firebase servers are down. It means that the request was rejected most likely due to a Firebase Security Rule issue.
Android Cloud Firestore task's return successfully when there is no internet connection. How?
I would like to simply get a callback when reading from DB fails, so I can show a dialog to the user about whether he has no internet connection.
The Firestore SDK doesn't throw an error when there is no internet connection, and it makes sense since Firestore is designed to work offline. Behind the scenes, Firestore SDK tries to reconnect until the devices regain connectivity. So not having an internet connection cannot be considered a failure. If you want to check for internet connectivity, the following answer might help:
- How to verify if user has network access and show a pop-up alert when there isn't
Please notice that Firestore has a built-in mechanism that can help know when an error occurs. So the failure callback occurs when Firestore servers reject the request due to a security rule issue.
There is a solution in which you can force the retrieval of data only from the cache or from the server. Here is the official documentation regarding source options:
- https://firebase.google.com/docs/firestore/query-data/get-data#source_options
iOS 14 How to trigger Local Network dialog and check user answer?
I did open DTS request and had conversion with Apple support team. Here is some important parts which I included below.
How to check is access granted or not
From support team:
For know, there is no such an API to check user permission.
From support team:
If the user declines, the connection fails. Exactly how it fails
depends on the network API you’re using and how you use that API.
- By default the connection will fail with
NSURLErrorNotConnectedToInternet
.- If you set
waitsForConnectivity
on the session configuration, the request will wait for things to improve. In that case you’ll receive
the-URLSession:taskIsWaitingForConnectivity:
delegate callback to
tell you about this. If the user changes their mind and enables local
network access, the connection will then go through.Unfortunately there’s no direct way to determine if this behaviour is
the result of a local network privacy restriction or some other
networking failure.
How to trigger this popup
From support team:
the problem here is that the local network permission alert is
triggered by outgoing traffic and you do not generate any outgoing
traffic. The only way around this is to generate some dummy outgoing
traffic in order to trigger this alert.I’ve seen other developers in this situation and the absence of a
direct API to trigger the local network permission alert is quite
annoying. I encourage you to file a bug about this.I’ve been discussing this issue with the local network privacy team
and our current advice for apps in your situation — that is, apps that
want to receive broadcasts but don’t send any local network traffic —
is as follows:
The system should do a better job of handling this. We’re tracking that as a bug rdar://problem/67975514. This isn’t fixed in the
current iOS 14.2b1 release but you should continue to test with iOS
beta seeds as they are released.In the meantime you can force the local network privacy alert to show by sending a message. We specifically recommend that you send a
message that’s roughly equivalent to the message you’re trying to
receive, so in your case that means sending an IPv4 UDP broadcast.
UPDATE
For iOS 14.2 - prompt is received for inbound traffic FIXED. Because of this you don't need below example for simulating traffic to triggering prompt.
Here is class for dummy outgoing traffic simulation:
example
That traffic will never leave the iOS device and thus, even if the
interface is asleep, it won’t wake it up. And even if it did wake up
the interface, the cost of that is trivial because you’re not doing it
over and over again, just once in order to trigger the local network
privacy alert.
Swift ios check if remote push notifications are enabled in ios9 and ios10
Updated answer after iOS 10 is using UNUserNotificationCenter
.
First you need to import UserNotifications
then
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { permission in
switch permission.authorizationStatus {
case .authorized:
print("User granted permission for notification")
case .denied:
print("User denied notification permission")
case .notDetermined:
print("Notification permission haven't been asked yet")
case .provisional:
// @available(iOS 12.0, *)
print("The application is authorized to post non-interruptive user notifications.")
case .ephemeral:
// @available(iOS 14.0, *)
print("The application is temporarily authorized to post notifications. Only available to app clips.")
@unknown default:
print("Unknow Status")
}
})
this code will work till iOS 9, for iOS 10 use the above code snippet.
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
Detect blocked popup in Chrome
Well the "magical time" you speak of is probably when the popup's DOM has been loaded. Or else it might be when everything (images, outboard CSS, etc.) has been loaded. You could test this easily by adding a very large graphic to the popup (clear your cache first!). If you were using a Javascript Framework like jQuery (or something similar), you could use the ready() event (or something similar) to wait for the DOM to load before checking the window offset. The danger in this is that Safari detection works in a conflicting way: the popup's DOM will never be ready() in Safari because it'll give you a valid handle for the window you're trying to open -- whether it actually opens or not. (in fact, i believe your popup test code above won't work for safari.)
I think the best thing you can do is wrap your test in a setTimeout() and give the popup 3-5 seconds to complete loading before running the test. It's not perfect, but it should work at least 95% of the time.
Here's the code I use for cross-browser detection, without the Chrome part.
function _hasPopupBlocker(poppedWindow) {
var result = false;
try {
if (typeof poppedWindow == 'undefined') {
// Safari with popup blocker... leaves the popup window handle undefined
result = true;
}
else if (poppedWindow && poppedWindow.closed) {
// This happens if the user opens and closes the client window...
// Confusing because the handle is still available, but it's in a "closed" state.
// We're not saying that the window is not being blocked, we're just saying
// that the window has been closed before the test could be run.
result = false;
}
else if (poppedWindow && poppedWindow.test) {
// This is the actual test. The client window should be fine.
result = false;
}
else {
// Else we'll assume the window is not OK
result = true;
}
} catch (err) {
//if (console) {
// console.warn("Could not access popup window", err);
//}
}
return result;
}
What I do is run this test from the parent and wrap it in a setTimeout(), giving the child window 3-5 seconds to load. In the child window, you need to add a test function:
function test() {}
The popup blocker detector tests to see whether the "test" function exists as a member of the child window.
ADDED JUNE 15 2015:
I think the modern way to handle this would be to use window.postMessage() to have the child notify the parent that the window has been loaded. The approach is similar (child tells parent it's loaded), but the means of communication has improved. I was able to do this cross-domain from the child:
$(window).load(function() {
this.opener.postMessage({'loaded': true}, "*");
this.close();
});
The parent listens for this message using:
$(window).on('message', function(event) {
alert(event.originalEvent.data.loaded)
});
Hope this helps.
check network status using network native
Finally l found it the problem . Several failed attempts have reached a conclusion :
constructor(private http: HTTP, public loadingController: LoadingController,public network: Network,
public alertController : AlertController, public toastController : ToastController) {
if (this.network.type == 'none'){
this.AlertNet()
}else if(this.network.type === 'wifi'){
this.getData()
}
this.network.onConnect().subscribe(()=> {
if(network.Connection.WIFI){
this.presentToastWithOptions()
}
});
this.network.onDisconnect().subscribe(()=> {
this.presentToast()
});
}
async presentToast() {
const toast = await this.toastController.create({
message: 'You dont have internet connection :(',
duration: 2000
});
toast.present();
}
async presentToastWithOptions() {
const toast = await this.toastController.create({
message: 'Internet connection is back :)',
showCloseButton: true,
position: 'top',
closeButtonText: 'Done'
});
toast.present();
}
async AlertNet(){
const alert = await this.alertController.create({
header: 'Alert',
subHeader: 'No internet',
message: 'You do not have an Internet connection. Please check your connection status',
buttons: [{
text: "Ok"
}]
});
await alert.present();
}
If you use onConnect
and onDisconnect
they are only working for detected connection . example if you are inside app and you switch off wifi onDisconnect
he will work to detected that and onConnect
same work if you switch on wifi or Mobile data .
if you want to detected your connection for first run for your app you can do with network.type
if (this.network.type == 'none'){
this.AlertNet()
}else if(this.network.type === 'wifi'){
this.getData()
}
when l used this code above and run app he is start to check my phone if he has internet connection or net . if he doesn't has he will show me alert immediately .
Related Topics
How to Find Intent Source in Android
Change Background of Progressdialog
Register to Be Default App for Custom File Type
How to Rename a File on Sdcard with Android Application
Set Permission for Getting User's Email Id from Facebook Login
How to Add External Jar Libraries to an Android Project from the Command Line
Need to Disable Expand on Collapsingtoolbarlayout for Certain Fragments
How to Programmatically Launch a Specific Application
Exif Orientation Tag Value Always 0 for Image Taken with Portrait Camera App Android
Get the Distance Between Two Locations in Android
How to Get the Selected Item from Listview
Notifications Fail to Display in Android Oreo (API 26)
Android Viewpager Setcurrentitem Not Working After Onresume
Cordova Android Requirements Failed: "Could Not Find an Installed Version of Gradle"
Save State of Activity When Orientation Changes Android
Android - Build a Notification, Taskstackbuilder.Addparentstack Not Working