Checking the connection on user's device.
I'm building a dictionary app (sanakirja). The app requires internet connection, so we need to check for the connection. Here's how I did it with PhoneGap's Connection plugin.
Create res/xml/plugins.xml file and paste this:
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" />
Add this to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Edit assets/www/index.html and paste this code:
<!DOCTYPE html>
<html>
<head>
<title>Sanakirja</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
if(networkState == Connection.UNKNOWN || networkState == Connection.NONE)
alert("Ei yhteyttä internetiin. Sovellus vaatii internet-yhteyden.");
}
</script>
</head>
<body>
</body>
</html>
You can test this on the emulator by setting Airplane mode on in the device settings. If there is no connection, the app will display an alert.
Ei kommentteja:
Lähetä kommentti