The Android Developer's Cookbook: Networking
- Reacting to the Network State
- Using SMS
- Using Web Content
- Social Networking
Read The Android Developer's Cookbook: Building Applications with the Android SDK, Second Edition and more than 24,000 other books and videos on Safari Books Online. Start a free trial today.
Network-based applications provide increased value for a user, in that content can be dynamic and interactive. Networking enables multiple features, from social networking to cloud computing.
This chapter focuses on the network state, short message service (SMS), Internet resource-based applications, and social networking applications. Knowing the network state is important to applications that fetch or update information that is available through a network connection. SMS is a communication service component that enables the exchange of short text messages between mobile phone devices. Internet resource-based applications rely on web content such as HTML (HyperText Markup Language), XML (eXtensible Markup Language), and JSON (JavaScript Object Notation). Social networking applications, such as Twitter, are important methods for people to connect with each other.
Reacting to the Network State
Knowing how and if a device is connected to a network is a very important facet of Android development. Applications that stream information from a network server may need to warn users about the large amount of data that may be charged to their accounts. Application latency issues may also be a concern. Making some simple queries enables users to find out if they are currently connected through a network device and how to react when the connection state changes.
Recipe: Checking for Connectivity
The ConnectivityManager is used for determining the connectivity of a device. This recipe can be used to determine what network interfaces are connected to a network. Listing 10.1 uses the ConnectivityManager to display if the device is connected via Wi-Fi or Bluetooth.
Listing 10.1. src/com/cookbook/connectivitycheck/MainActivity.java
package com.cookbook.connectivitycheck; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv_main); try { String service = Context.CONNECTIVITY_SERVICE; ConnectivityManager cm = (ConnectivityManager)getSystemService(service); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; boolean isBT = activeNetwork.getType() == ConnectivityManager.TYPE_BLUETOOTH; tv.setText("WiFi connected: "+isWiFi+"\nBluetooth connected: "+isBT); } catch(Exception nullPointerException) { tv.setText("No connected networks found"); } } }
Listing 10.1 uses the constants TYPE_WIFI and TYPE_BLUETOOTH to check for connectivity on these networks. In addition to TYPE_WIFI and TYPE_BLUETOOTH, the following constants can also be used to determine connectivity:
- TYPE_DUMMY—For dummy data connections
- TYPE_ETHERNET—For the default Ethernet connection
- TYPE_MOBILE—For the default mobile data connection
- TYPE_MOBILE_DUN—For DUN-specific mobile data connections
- TYPE_MOBILE_HIPRI—For high-priority mobile data connections
- TYPE_MOBILE_MMS—For an MMS-specific mobile data connection
- TYPE_MOBILE_SUPL—For an SUPL-specific mobile data connection
- TYPE_WIMAX—For the default WiMAX data connection
Figure 10.1 shows an application running with the code from Listing 10.1. Even though Bluetooth has been enabled, it reports false for being connected because it does not currently have an active connection.
Figure 10.1 Checking for device connectivity
Recipe: Receiving Connectivity Changes
A broadcast receiver can be used to check the status of network connectivity when it is necessary to react to changes in connectivity status.
A broadcast receiver can be declared in the application manifest, or it can be a subclass inside the main activity. While both are accessible, this recipe uses a subclass in conjunction with the onCreate() and onDestroy() methods to register and unregister the receiver.
As this recipe checks for connectivity, the following permissions need to be added to the application manifest:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Listing 10.2 shows the code needed to check for connectivity changes. When a change is detected, the application will display a toast message informing the user of the change.
Listing 10.2. src/com/cookbook/connectivitychange/MainActivity.java
package com.cookbook.connectivitychange; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends Activity { private ConnectivityReceiver receiver = new ConnectivityReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); receiver = new ConnectivityReceiver(); this.registerReceiver(receiver, filter); } @Override public void onDestroy() { super.onDestroy(); if (receiver != null) { this.unregisterReceiver(receiver); } } public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { Toast.makeText(context, "WiFi is connected", Toast.LENGTH_SHORT).show(); } else if (networkInfo != null) { Toast.makeText(context, "WiFi is disconnected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "No active connection", Toast.LENGTH_SHORT).show(); } } } }
Figure 10.2 shows the message that appears when Wi-Fi is connected. Figure 10.3 shows the message that appears when both Wi-Fi and mobile data have been disconnected.
Figure 10.2 When Wi-Fi is enabled, a toast message appears informing the user of the connection
Figure 10.3 Wi-Fi and mobile data are disabled, so a toast informing the user of the lack of network connectivity is displayed