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
2
3
<manifest xlmns:android="https://schemas.android.com/apk/res/android"
package="com.example.a10_01_sms">
<uses-permission android:name="android.permission.SEND_SMS" />

Ask user to grant permission

1
2
3
4
5
6
7
if(ContextCompat.checkSelfPermission(this, 
Manifest.permission.SEND_SMS
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
REQUEST_SEND_SMS);
}

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
2
3
4
private void sendSMS(String phoneNumber, String message){
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String str = "SMS from ";
if (bundle != null)
{
//---retrieve the SMS message received---
// Each msgs[i] can only store 160 chars
msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (int i = 0; i < msgs.length; i++)
{
//---get the message body---
str += msgs[i].getMessageBody().toString();
}
}
//---display the new SMS message If you need to---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Log.d("SMSReceiver", str);
}
}
  • 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
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a10_01_sms">
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
1
2
3
4
5
6
7
8
9
10
11
<!--android:enabled means the System can run this receiver -->
<!--android:exported means Other apps can run this receiver-->
<receiver
android:name=".SMSReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

To ask user to grant permission for recieveing SMS

1
2
3
4
5
6
7
if(ContextCompat.checkSelfPermission(this, 
Manifest.permission.RECEIVE_SMS
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
REQUEST_RECEIVE_SMS);
}

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
2
3
4
5
6
7
8
9
10
11
private void sendEmail(String[] emailAddresses, String[] carbonCopies, 
String subject, String message){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
String[] to = emailAddresses;
String[] cc = carbonCopies;
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Email"));
}

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
2
3
4
5
6
7
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNTECTIVITY_SERVICE);

NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null) {
Log.e("NETWORK", "No network");
}
Log.e("NETWORK", String.valueOf(info.isConnected()));

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
2
3
4
5
6
private Socket mSocket = null;
mSocket = new Socket(ServerIP, PORT);
mPrintWriter = new PrintWriter(mSocket.getOutputStream());
String str = mEditText.getText().toString();
mPrintWriter.print(str); //Send the str to destination
mPrintWriter.flush(); //Flush the data in buffer to ensure no corruption

Server

Listen and Accept in Socket

The service process keeps listening, accepts incoming request, and establishes connection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Server {
public static void main() {
new Server();
}
public Server() {
mServerSocket = new ServerSocket(PORT);
while (true) {
// Waits for an incoming request and blocks
// until the connection is opened
Socket client = mServerSocket.accept();
br = BufferedReader(new InputStreamReader(client.getInputStream()));
if (strMsg = br.readLine() != null){
// Do something...
}
}
}
}

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
2
3
4
5
6
7
8
9
10
11
12
mThread = new Thread(mRunnable);
mThread.start();

private Runnable mRunnable = new Runnable
{ public void run()
{ if(strMsg = br.readLine() != null) // Push a msg to the thread’s queue.
{ mHandler.sendMessage(msg); }};

// Handler object for Inter-thread communication in Android
private Handler mHandler = new Handler()
{ public void handleMessage(Message msg) //Execute what we need to do
{ mEditText.append(strMsg); }};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com.hk");
try {
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) //Get the content from HTTP site
{
Log.e("HTTP", line);
}
} catch (IOException e) {
e.printStackTrace();
}
//Go to www.google.com.hk and print out the content of the response

Java Networking API

1
2
3
4
5
6
7
8
9
10
11
12
13
String urltext = "http://www.google.com.hk";
URL url;
String inputLine;
try {
url = new URL(urltext);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((inputLine = in.readLine()) != null) //Get the content from the site
{
Log.v("TTT", inputLine);
} in.close();
} catch (Exception e) {
e.printStackTrace();
}

Search Google in Android using Intent / Google API

Besides HTTP, We can use an Intent to actually Search in Google.

1
2
3
4
Intent intent = new Intent();
Intent.setAction(Intent.ACTION_WEB_SEARCH);
Intent.putExtra(SearchManager.QUERY, "Things you want to search");
startActivity(intent);

We can also use Google API to Search Google in Android.

https://developers.google.com/custom-search/v1/using_rest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String googleService = "http://ajax.googleapis.com/ajax/services/language/ translate?v=1.0&langpair=en%7Czh-TW&q="; //Google Translate API
try {
url = new URL(googleService);
connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder()
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = new JSONObject(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}

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
2
3
4
mWebview = findViewById(R.id.WebView01); 
mWebview.loadUrl("http://google.com/");

WebSettings webSettings = mWebview.getSettings(); webSettings.setBuiltInZoomControls(true);

Android - Networking (Wi-Fi, GPS, Bluetooth and NFC)

Wi-Fi

GPS Positioning

Android implements GPS in the Location Manager

Bluetooth

NFC