Android - Networking
Android - Networking
- Messaging
- SMS Messaging
- Sending Email
- Socket and HTTP
- Wi-Fi
- GPS Positioning
- Bluetooth
- NFC
SMS Messaging
Android comes with a built-in SMS application that enables you to send and receive SMS messages
- in some cases, you might want to integrate SMS capabilities into your Android application.
Sending SMS Messages
In AndroidManifest.xml
1 | <manifest xlmns:android="https://schemas.android.com/apk/res/android" |
Ask user to grant permission
1 | if(ContextCompat.checkSelfPermission(this, |
SmsManager class is used to send an SMS message programmatically
Unlike other classes, you do not directly instantiate this class
Instead, you call the getDefault() static method to obtain an SmsManager object and send the SMS message using the sendTextMessage() method
1 | private void sendSMS(String phoneNumber, String message){ |
The five arguments to the sendTextMessage() method:
- destinationAddress - Phone number of the recipient
- scAddress - Service center address; use null for default SMSC
- Text - Content of the SMS message
- sentIntent - Pending intent is broadcast when the message is successfully sent
- deliveryIntent - Pending intent is broadcast when the message is delivered to the recipient
Note: you would have to pay the fees incurred from sending all those SMS messages on a real Android device using your sim card
The free Android emulator provides that capability
- The four-digit number that appears above your emulator is its “phone number.” The first emulator session that you open is typically 5554.
SMSReceiever with BroadcastReceiver
The default SMS app of the Android OS will receive the SMS message.
You can also implement the Broadcast Receiver to receive the SMS in your own app
To listen for incoming SMS messages, you create a BroadcastReceiver class
When an intent is received, the
onReceive()
method is called, which needs to be overridden
1 | public class SMSReceiver extends BroadcastReceiver { |
- Now, you have the SMSReceiver class, what else do you need to set up in order to listen to the SMS receive broadcast?
- Refer to the “Sending SMS Messaging” and the steps to register the BroadcastReceiver
In AndroidManifest.xml
1 |
|
1 | <!--android:enabled means the System can run this receiver --> |
To ask user to grant permission for recieveing SMS
1 | if(ContextCompat.checkSelfPermission(this, |
Sending Email
The Gmail/Email application on Android enables you to configure an email account using POP3 or IMAP
- Besides sending and receiving emails using the Gmail/Email application, you can also send email messages programmatically from within your Android application
- Achieved by
Intent
You use an Intent object and set the various parameters using the setData()
, putExtra()
, and setType()
methods
1 | private void sendEmail(String[] emailAddresses, String[] carbonCopies, |
Manage connections
Android use ConnectivityManager to manage connntections on phone.
- Monitor network connections (Wi-Fi, HSDPA, LTE, etc.)
- Send broadcast intents when network connectivity changes
- Attempt to “fail over” to another network when connectivity to a network is lost
- Provide an API that allows application to query the state of the available networks
To check if user’s device is connected to Network:
1 | ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNTECTIVITY_SERVICE); |
Press F8 to connect / disconnect network in emulator
Some Useful Feature of ConnectivityManager
- Ensure a network route to the specified host exists
- ConnectivityManager.requestRouteToHost
- Declare to start using the named feature
- ConnectivityManager.startUsingNetworkFeature
- Check background data status
- ConnectivityManager.getBackgroundDataSetting
- Broadcast Receiver of networks status change
- ConnectivityManager.CONNECTIVITY_ACTION
Socket Programming
- A socket is an end-point in the communication link
- In Java, we use Socket and ServerSocket classes
- Socket as Client
- ServerSocket as Server
- Socket belongs to the Transport Layer
- Socket = IP + Port Number
Client
1 | private Socket mSocket = null; |
Server
Listen and Accept in Socket
The service process keeps listening, accepts incoming request, and establishes connection
1 | public class Server { |
Thread and Handler
For Socket, we should use a Thread on Android for receiving message because it keeps looping
- To use a Thread so It can process something simultaneously
- Independent to each other
1 | mThread = new Thread(mRunnable); |
Android’s mechanism to send and process Message and Runnable objects associated with a thread’s MessageQueue
- Each Handler instance is associated with a single thread and that thread’s message queue
- A Handler is bound to the thread/message queue of the thread that creates it
- Post(Runnable) to enqueue a Runnable obj
- sendMessage(Message) to enqueue a Message Obj containing a bundle of data
- handleMessage(Message) to process a Message
Android Network API
When we do the HTTP Request, we can have 2 ways to do it:
- Apache HTTP Component Library
- A toolset of low level Java components focused on HTTP and associated protocols
- Java Networking API
- Basic features
Apache HTTP Component Library
1 | HttpClient client = new DefaultHttpClient(); |
Java Networking API
1 | String urltext = "http://www.google.com.hk"; |
Search Google in Android using Intent / Google API
Besides HTTP, We can use an Intent to actually Search in Google.
1 | Intent intent = new Intent(); |
We can also use Google API to Search Google in Android.
1 | String googleService = "http://ajax.googleapis.com/ajax/services/language/ translate?v=1.0&langpair=en%7Czh-TW&q="; //Google Translate API |
How to use Google Translate API in Android Studio projects?
Android Webview
A View that displays web pages.
- Used to Create web-based application
- You can roll your own web browser or display online content within your Activity
1 | <WebView android.id="@+id/Webview01"/> |
1 | mWebview = findViewById(R.id.WebView01); |
Android - Networking (Wi-Fi, GPS, Bluetooth and NFC)
Wi-Fi
GPS Positioning
Android implements GPS in the Location Manager