27
Laboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking, SMS, files and concurrency lab In this lab we are going to do a little bit more programming by ourselves than in the former lab. As always consult various tutorials and examples on the Internet to solve your problems. Browse/read thru every chapter before you begin working with the task. The work to report in this lab is found in the 4.1.4, 4.2.6 and 4.3.3 section. See labinstruktion.pdf for general instructions regarding laborations. Table of Contents 4 Android – Networking, SMS, files and concurrency lab......................................................... 1 4.1 Networking, multiple activities and background jobs......................................................1 4.1.1 Load an image over HTTP requirements specification............................................ 1 4.1.2 Preparation................................................................................................................ 2 4.1.3 Help.......................................................................................................................... 3 4.1.4 Report....................................................................................................................... 5 4.2 Cell ID tracker.................................................................................................................. 6 4.2.1 Cell ID requirements specification........................................................................... 6 4.2.2 Background and further description......................................................................... 6 4.2.3 Higher precision location alternative........................................................................7 4.2.4 Deprecated since the OpenCellID API key does not work anymore – but section may contain very useful information................................................................................. 9 4.2.5 References...............................................................................................................11 4.2.6 Report..................................................................................................................... 12 4.3 Send and receive SMS....................................................................................................13 4.3.1 SMS tutorial............................................................................................................13 4.3.2 Resources for SMS................................................................................................. 17 4.3.3 Report..................................................................................................................... 17 4.3.4 Runtime permissions explained.............................................................................. 17 4.3.5 Runtime permission samples.................................................................................. 19 4.4 List with topics you need to understand before next laboration.....................................19 4.5 Lab Feedback................................................................................................................. 19 4.6 Using a JAR or module library with Android Studio.....................................................20 4.7 Using a library in Eclipse (from GitHub).......................................................................21 4.1 Networking, multiple activities and background jobs This app should download an image from a website and show it for the user. It shall contain two activities. 4.1.1 Load an image over HTTP requirements specification A main Activity Högskolan Dalarna Telefon: 023-77 80 00 Röda vägen 3 Telefax: 023-77 80 50 781 88 BORLÄNGE URL: http://www.du.se/ 1

4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4 Android – Networking, SMS, files and concurrency lab In this lab we are going to do a little bit more programming by ourselves than in the former lab. As always consult various tutorials and examples on the Internet to solve your problems.

Browse/read thru every chapter before you begin working with the task. The work to report in this lab is found in the 4.1.4, 4.2.6 and 4.3.3 section.

See labinstruktion.pdf for general instructions regarding laborations.

Table of Contents4 Android – Networking, SMS, files and concurrency lab.........................................................1

4.1 Networking, multiple activities and background jobs......................................................14.1.1 Load an image over HTTP requirements specification............................................14.1.2 Preparation................................................................................................................24.1.3 Help..........................................................................................................................34.1.4 Report.......................................................................................................................5

4.2 Cell ID tracker..................................................................................................................64.2.1 Cell ID requirements specification...........................................................................64.2.2 Background and further description.........................................................................64.2.3 Higher precision location alternative........................................................................74.2.4 Deprecated since the OpenCellID API key does not work anymore – but section may contain very useful information.................................................................................94.2.5 References...............................................................................................................114.2.6 Report.....................................................................................................................12

4.3 Send and receive SMS....................................................................................................134.3.1 SMS tutorial............................................................................................................134.3.2 Resources for SMS.................................................................................................174.3.3 Report.....................................................................................................................174.3.4 Runtime permissions explained..............................................................................174.3.5 Runtime permission samples..................................................................................19

4.4 List with topics you need to understand before next laboration.....................................194.5 Lab Feedback.................................................................................................................194.6 Using a JAR or module library with Android Studio.....................................................204.7 Using a library in Eclipse (from GitHub).......................................................................21

4.1 Networking, multiple activities and background jobs

This app should download an image from a website and show it for the user. It shall contain two activities.

4.1.1 Load an image over HTTP requirements specification

A main Activity

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

1

Page 2: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

◦ Having a button Load Image.

◦ Having an EditText containing the URL to the image we want to download. The URL string should be remembered at next start and have a default value.

◦ The URL string should be sent to the second activity when the button is pressed.

The second Activity

◦ When pressing the button a new activity should start downloading and displaying the image. Only the image should be visible in the second activity. Use an ImageView to hold the image.

◦ Before starting the download a Toast should be displayed showing if any network is available on the phone.

◦ During the download a progress bar dialog should be visible.

◦ You should use an AsyncTask for the background job.

◦ Rotating the device should not make the image disappear from the screen when theimage has been downloaded.

You have two options to solve this problem. Either save the image bitmap (efficient) or the URL to the image (not efficient) in the onSaveInstanceState() callback method. Then either load the url again or restore the saved image.

Here is an example how to save the image:outState.putParcelable("BitmapImage", mBitmap);and to restore the imagemBitmap = (Bitmap) savedInstanceState.getParcelable("BitmapImage");

As mentioned - saving and restoring the image is more efficient and nicer to the users data plan.Parcelable is for objects/classes that implements the Parcelable interface which theBitmap class and many other Android API classes do. You can implement the Parcelable interface for your own classes as well. Read more about Parcelable here: http://developer.android.com/reference/android/os/Parcelable.html

4.1.2 PreparationThe tutorials you need to investigate to solve this task is mainly found on: http://www.vogella.com/android.html

Android Networking Android background processing with Handlers, AsyncTask and Loaders Android Persistence with preferences and files The course presentation material

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

2

Page 3: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.1.3 HelpStrictModeStrictMode can permit long operations in the main thread. You can enable StrictMode for testing purposes with:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

StrictMode allows to setup policies in your application to avoid doing incorrect things, but also permit things that should be avoided/forbidden. You can put the code in onCreate().

Remove the StrictMode code after you verified that your application works.

Here is a couple of helper methods for downloading an image in the background, see theHttpDownload example for a full listing.

// AsyncTask configurationprivate class DownloadImageTask extends AsyncTask <URL, Void, Bitmap> {

protected Bitmap doInBackground(URL... urls) {return downloadImage(urls[0].toString());

}

protected void onPostExecute(Bitmap result) {imageView.setImageBitmap(result);

}}

// download and return an imageprivate Bitmap downloadImage(String URL) {

Bitmap bitmap = null;InputStream is;

try {is = openHttpConnection(URL);bitmap = BitmapFactory.decodeStream(is);is.close();

}catch (IOException ex) {

ex.printStackTrace();}catch (Exception ex) {

ex.printStackTrace();}return bitmap;

}

// method that returns an InputStream from an URL

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

3

Page 4: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

private InputStream openHttpConnection(String urlString) throws IOException {

InputStream is = null;int response = -1;

URL url = new URL(urlString); URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection)) throw new IOException("Not a HTTP connection");

try{HttpURLConnection httpConn = (HttpURLConnection) conn;httpConn.setAllowUserInteraction(false);httpConn.setInstanceFollowRedirects(true);httpConn.setRequestMethod("GET");httpConn.connect();

response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) {

is = httpConn.getInputStream(); }else Log.e("lab4", "openHttpConnection() Response: " + response);

} catch (Exception ex) {

throw new IOException("Error connecting"); }return is;

}

Sometimes when you perform background jobs, you want to lock the UI. One can use a ProgressDialog for this.

Fig 1. ProgressDialog.

Here is an example for how to use the ProgressDialog.

ProgressDialog mDialog = ProgressDialog.show(YourActivity.this, "", "Pleasewait for few seconds...", true);// To dismiss a ProgressDialog when the task is done use mDialog.dismiss();

If you want your download task take longer time you can restrict the emulators networkspeed

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

4

Page 5: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

Navigate to the Android Emulators Extended controls: Overflow menu (...) > Cellular > Network type. Adjust Network Speed to the desired value. GSM is slowest.

If it does not work select a larger image to download or unplug the network cable for a while.

Example program is attached in lab41.apk

Result in fig2, fig3 and fig4 below.

Fig. 2, 3 and 4 describing an overview of the app function.

4.1.4 ReportImplement your app according to the requirements specification. Then hand in the project source code in a packed archive. It should contain a runnable version (.apk file) of your app inthe [app-src]\bin or /app//build/outputs folder. If possible demonstrate the functionality of your app with a video and possibly supplement the video with audio. The built in recording in Android is explained here: https://guides.codepath.com/android/Recording-Video-of-an-Android-Device

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

5

Page 6: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.2 Cell ID trackerFirst read thru this part of the lab and then create a new Android project with a suitable Activity layout. You will probably develop this program further in the following labs so put some thought into it so you can change layout easy. For now… plain buttons are enough.

Later on you can for example choose one of the recent standard navigation types as: Master/Detail Flow, Navigation Drawer Activity or Tabbed Activity. Or other layout combinations with or without an App Bar and Fragments.

4.2.1 Cell ID requirements specification The app should continuously save the Cell ID (the cell tower antenna id), LAC

(Location Area Code), MCC (Mobile Country Code), MNC (Mobile Network Code) and date time to a log file when the mobile phone changes the cell tower it is connected to.

The app state (recording or not recording) and current cell network values should be visible on the screen in some form.

With a button or via some other user interaction the user should be able to view current latitude and longitude translated from the 4 mobile network values described above.

If you got variables that is accessed by more than one thread you should protected them against wrong readings i.e. half updated variables with critical regions in the code.

When exiting the program everything must stop sampling in a graceful way regardless of current app state.

Since the log file is written to the sdcard (external storage) you need to implement runtime permissions if you are using API-23 and newer. Consult the sections 4.3.4 and4.3.5 for how to implement this.

4.2.2 Background and further descriptionWe are going to implement an app that collects cellular network values into a file in Comma Separated Values (CSV) format. By using the cellular network values one can locate a phone pretty well depending on the density of the cell towers location.The CSV file should contain the following fields: <CELLID>;<LAC>;<MCC>;<MNC>;<DATE-TIME>. Usually it is better to choose semicolon as delimiter if you are going to handle floating point numbers, since mixing dots and commas can be troublesome afterwards regarding localization.

Note that not all phones have access to the hardware in this way as Android so one easilycan do this!

Try to only collect values when the MS/UE (Mobile Station/User Equipment) change its Cell ID.

We are also going to translate the cell values into latitude and longitude and display it. So we in later labs can show the cell tower location (or the users approximated location) on a map. See fig 5 for a general description how this works. Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

6

Page 7: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

Fig 5. Cell id to latitude and longitude conversion.

4.2.3 Higher precision location alternativeAn alternative to the OpenCellid API solution in section 4.2.4 is “The Google Maps Geolocation API”. Googles solution works much like the OpenCellid database in fig 5 but with much higher accuracy and dependability since its cell id database and cloud servers are better maintained. It can also use Wi-Fi access point parameters for even better location precision.

Earlier there was only a Google Maps Geolocation API for Business version which did come with a cost, but now there is a standard Google Maps Geolocation API free for limited use. It is found here: https://developers.google.com/maps/documentation/geolocation/intro

1. Follow the web page instructions above to get a standard Google Maps Geolocation API key. You can do 2500 requests per day for free. If you got problems take a look at the lab 5setup Maps instructions since they are more detailed.

2. Configure your API key and enable Google Maps Android API and Google Maps Geolocation API support on the API manager/console web page. You only need Geolocation just now but we are going to use Maps later on. In short…

In the Google API:s console left hand menu dropbox select Create project ... In the shown dialog give the project a name as: Location-API or any name. Select europe-west as App Engine region and press Create button. Make sure “Location-API” is selected in the left hand menu dropbox. Press + ENABLE API and select/search Google Maps Android API and Google Maps

Geolocation API. Press ENABLE to enable the API. Press Dashboard end verify that it is added. Then press the API row and press the

Credentials button to generate your API key. Make sure there is no restriction on the key since it can make things difficult. If you

add restrictions you need to add a package name and fingerprint. If you want to delete a project, click Project settings on the overflow menu.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

7

Page 8: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

3. Wait for at least 5 minutes so the change can propagate. Then test your API key with cURLhttps://curl.haxx.se/ and the sample JSON request data according to the documentation page above. As:

C:\bin>curl -d @location.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY

When it work you should get a JSON response as:

{ "location": { "lat": 37.4248297, "lng": -122.07346549999998 }, "accuracy": 1145.0}

4. Now you can begin doing your app. Instead of using a lot of complicated code to manage the JSON requests and responses we use the Retrofit library https://github.com/square/retrofit in version 2+ with a built-in “converter” or JSON parser (Gson). Add this dependencies to gradle:

dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.google.android.gms:play-services-location:9.6.1' compile 'com.google.code.gson:gson:2.7' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'}

In the google geolocationapi folder I have included some classes and methods (helper-methods.txt) that you can use.Basically all you have to do is to create an UI. Gather the different cell id parameters and store them as member variables. Bind getPositionByCellId(View view) and getPositionByWiFi(View view) to buttons and/or a timer. These methods use the Retrofit library and will build a request, send the REST call and receive an answer in the success or failure callback methods.

5. Included in the lab is also an example app where some of the requested functionality is demonstrated in lab42-geolocationapi.apk.Every time you press a GET… button a cell id or WiFi geolocation request is made and a translated lat/lng position is sent in response from Google.To get the WiFi position we need to get the local Access Point/Gateway MAC address which is visible for connected clients via the getBSSID() API-method. If it fails fill in your APs local IP address and the included public static String getMacFromArpCache(String ip) method will return a valid MAC address which can be used.

Things to know of value

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

8

Page 9: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

You need a “Google APIs System Image” emulator system image based AVD since we use Google Play services library functions in this solution.

Google Developers Console is located at: https://console.developers.google.com. You need a Google/Gmail account/address to be able use the Geolocation API. If you

do not got it yet you can create one here: https://accounts.google.com/SignUp. If you got problems with the API key follow this guide:

https://developers.google.com/maps/documentation/android-api/signup and set the keyto unrestricted.

When you include the play service lib the number of method references may exceed 64K. Put multiDexEnabled true in your gradle.build file, reference: http://stackoverflow.com/questions/36638756/unable-to-build-apk-the-number-of-method-references-cannot-exceed-64k

The easiest way to get your SHA-1 fingerprint is: with Eclipse from the menu: Window > preferences > Android > Build > SHA1

fingerprint. with Android Studio there is at least two ways, one via the console and another when

you have created your project. Reference: http://stackoverflow.com/questions/27609442/how-to-get-the-sha1-fingerprint-certificate-in-android-studio-for-debug-mode

4.2.4 Deprecated since the OpenCellID API key does not work anymore – but section may contain very useful information

I have included a modified utility class: OpenCellID.java from the article:”Adding location to a non GPS phone: introducing CellID” (see references). This class can be used with the OpenCellID database API. An API key, which is found in Fronter news (I do not want to publish it here) is needed for cell/get to work.

You may need to expand the OpenCellID class with appropriate methods. If you want, you can also send your values to http://www.opencellid.org so their database is getting better. To do that you can use the library found at: http://wiki.opencellid.org/wiki/Android_library.

Instructions how to use a libraries are found in section 4.6 and 4.7.

A problem with the original OpenCellID.java code is that it is not compatible with the latest OpenCellID API. To correct this, use the XMLParser.java and the updated OpenCellID.java code that I have attached in the lab folder. Call the spliteResultXML(); instead in this version which use the XMLParser class.

Note that in API-23 and later you may have to add the Apache HTTP classes as a library in the build.gradle file as:

android { useLibrary 'org.apache.http.legacy'}

Otherwise use the more efficient HttpURLConnection class. Se here for reference:https://developer.android.com/about/versions/marshmallow/android-6.0.html

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

9

Page 10: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

> API level 22 to 23Also note that you must add the network code for the OpenCellID calls in a thread or a background task (AsyncTask).

Basically you can use the OpenCellID class above and kick off a method like getLatLngOpenCellID() in your Cell Id Activity where you do everything dealing with getting lat/lng from your network parameters.

To get the needed mobile cell parameters at once when they have changed you have two options.

1. Either read them rather often (polling timer) and compare them to previous values if they have changed. The drawback is that you can miss a reading if the device change the values faster than you read them.

2. Or set up the Telephony Manager with a onCellLocationChanged(CellLocation location) listener that immediately will be called if the device cell parameters change. This however only works on physical phones.

A problem on the emulator is that these parameters do not change at all so you have to simulate them in some way (with a timer, handler or other suitable method).

To solve this check the: http://opencellid.org/ > map and zoom into your location (the map is a bit slow so wait for it to load). Find some mobile cell towers close to where you live and click on the tower and note the cell id data. Try to get cell ids with the same LAC. To set the cell id randomly you can use:

private int getRandCID(){

final int CELLIDS [] = {4786673, 4798521, 4786670,...};Random random = new Random();return CELLIDS[random.nextInt(CELLIDS.length)];

}

// retrieve a reference to an instance of TelephonyManagerTelephonyManager telephonyManager =

(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);GsmCellLocation cellLocation =

(GsmCellLocation)telephonyManager.getCellLocation();

// public void GsmCellLocation.setLacAndCid (int lac, int cid), hard coded lac/cidcellLocation.setLacAndCid(73, getRandCID());

The values for MCC and MNC you can hard code to “240” (Sweden) and “05” (Tele2) or suitable MNC. If you cannot find the same LAC you can cheat (hard code) it in some way with a switch case or something.

Protecting variables against half updated/mixed readings

If it is possible that the cell id variables are accessed by more than one thread at the same timeone must protect the variables in some way. This can be done by locking critical sections of the code. Every time you access critical resources in your code you do it in critical regions declared with the keyword synchronized.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

10

Page 11: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

// declaring an object that we use as a lock private static final Object mObjLock = new Object();

// a critical region in your code synchronized(mObjLock){

// threaded code which access shared resources, only one thread at once can// manipulate resources inside the braces

}

One can declare a method synchronized as well.

private synchronized void methodName() {// threaded code}

Example program is attached in lab42-opencellid.apk

Result in fig 6 below. The user has just pressed the “Show current Lat/Lng” button which use the OpenCellID API to retrieve a latitude, longitude location. The example program use method 1 when running on an emulator and method 2 when running on a physical device. Sampling is only active when the screen is visible.

Fig 6. Cell ID sampling to latitude and longitude conversion.

4.2.5 References OpenCellID API: http://wiki.opencellid.org/wiki/API List of mobile country codes: https://en.wikipedia.org/wiki/Mobile_country_code Adding location to a non GPS phone: introducing CellID:

http://mobiforge.com/developing/story/adding-location-a-non-gps-phone-introducing-cellid

Get location of Cell ID, from opencellid.org using HttpGet(): http://android-coding.blogspot.se/2011/06/get-location-of-cell-id-from.html

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

11

Page 12: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

Public Cell ID databases [closed]: http://stackoverflow.com/questions/82184/public-cell-id-databases

Minigps: http://www.minigps.net/map.html

4.2.6 ReportImplement your app according to the requirements specification. Then hand in the project source code in a packed archive. It should contain a runnable version (.apk file) of your app inthe [app-src]\bin or /app//build/outputs folder. If possible demonstrate the functionality of your app with a video and possibly supplement the video with audio. The built in recording in Android is explained here: https://guides.codepath.com/android/Recording-Video-of-an-Android-Device

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

12

Page 13: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.3 Send and receive SMS

4.3.1 SMS tutorial

Note that since API 23 (Android 6) a new permission model is introduced. You need to ask the user for permission to use SMS and other things as GPS etc. I have included a tutorial in: section 4.3.4 Runtime permissions explained.

Step 1Create a SMS project with the Activity SMS.In the AndroidManifest.xml file, add two Uses Permissions - SEND_SMS and RECEIVE_SMS.

Step 2In the main.xml and strings.xml. Add two TextView to the display, “Enter the phone number of recipient” and “Message”.Add two EditText with IDs txtPhoneNumber and txtMessage.Add a Button with Text "Send SMS“ and ID btnSendSMS.

Make sure the controls fill the whole screen width according to fig 7. The Message should also have room for at least 3-4 lines.

Fig.7. SMS design with two edit texts and one button.

Step 3Import Classes and Interfaces and put the code below into the SMS class onCreate() method.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

13

Page 14: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

btnSendSMS = (Button) findViewById(R.id.btnSendSMS);txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);txtMessage = (EditText) findViewById(R.id.txtMessage); btnSendSMS.setOnClickListener(new View.OnClickListener(){

public void onClick(View v) {

String phoneNo = txtPhoneNo.getText().toString(); String message = txtMessage.getText().toString();

if(phoneNo.length() > 0 && message.length() > 0) sendSMS(phoneNo, message);

elseToast.makeText(getApplicationContext(),

"Please enter both phone number and message.", Toast.LENGTH_SHORT).show();

}});

Step 4To send a SMS message we use the SmsManager class. To instantiate this class call the getDefault() static method.

The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time by another application.

private void sendSMS(String phoneNumber, String message) {

PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMS.class), 0);

SmsManager sms = SmsManager.getDefault(); // Get the default instanceof the SmsManager

sms.sendTextMessage(phoneNumber, null, message, pi, null);}

Now try the program in the emulator. In order to test the application you need to start another AVD (do not use the same AVD system image – it will fail) to receive the SMS. The phone number is the port number displayed at top (after the semi colon) in the emulator. You can usethe native built-in Android SMS program to receive the SMS.

Step 5Now we will build our own SMS receiver. Create and add the class: public class SmsReceiver extends BroadcastReceiver

In the SmsReceiver class override the onReceive() method. The message is attached to the Intent.

The SMS messages are stored in an object array PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. If you want to dig deeper into the PDU format, this web page have all the information: http://www.gsm-modem.de/sms.html. We are going to do this later on anyway in a following course :-)

The SMS is in this solution displayed using the Toast class. Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

14

Page 15: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

@Overridepublic void onReceive(Context context, Intent intent){

//---get the SMS message passed in---Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null;String str = "";

if (bundle != null){

//---retrieve the SMS message received---Object[] pdus = (Object[]) bundle.get("pdus");msgs = new SmsMessage[pdus.length];

for (int i=0; i<msgs.length; i++) {

msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); str += " :";str += msgs[i].getMessageBody().toString();str += "\n";

}//---display the new SMS message---Toast.makeText(context, str, Toast.LENGTH_LONG).show();

} }

Step 6In the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class. See fig 8.

<receiver android:name=".SmsReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /></intent-filter>

</receiver>

Fig 8. Eclipse AndroidManifest.xml editor.

In order to test the SmsReceiver function you can either start another AVD and send a SMS message or use the Android Device Monitor > DDMS > Emulator Control tab > Telephony Actions. The most convenient method is however to use the emulator Extended controls.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

15

Page 16: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

To send a SMS or make a telephone call in Android Studio or Eclipse using ADM/DDMS: Start Android Device Monitor and/or Switch to the DDMS view. Navigate to the Emulator Control tab. Then mark an emulator who is going to receive the SMS or call in the Devices tab and

put in the Incoming number (which is the calling/sending number). Then press Call or text a SMS and press Send.

See fig 9 and 10.

Fig 9. Android Device Monitor and the DDMS view.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

16

Page 17: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

Fig 10. A SMS was received.

4.3.2 Resources for SMS Android developers - http://developer.android.com/index.html SMS Messaging in Android: https://mobiforge.com/design-development/sms-

messaging-android

4.3.3 ReportImplement a SMS app that can receive and send SMS. Then hand in the project source code in a packed archive. It should contain a runnable version (.apk file) of your app in the [app-src]\bin or /app//build/outputs folder. If possible demonstrate the functionality of your app with a video and possibly supplement the video with audio. The built in recording in Android is explained here: https://guides.codepath.com/android/Recording-Video-of-an-Android-Device

4.3.4 Runtime permissions explainedThis text is taken from: https://plus.google.com/+JoannaGSmith/posts/h4DuTT7tDKn

Marshmallow introduced Runtime Permissions, and that seems to be all anyone is talking about this summer. But that’s because prompting for a long list of permissions at install can intimidate users, and that’s not good for anyone. So apps targeting Marshmallow now have to put these permission requests into a context, by asking for them when the user is trying to use the relevant feature.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

17

Page 18: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

As great as this is, I’m sure that you’ve thought to yourself “that’s okay, I just won’t update toMarshmallow until I have to.” Updating your app isn’t as daunting as you might think, though. You simply need add a few lines of code that build in checks and graceful failures. Sohere’s a handy guide to walk you through it.

Step 1: check the platform. If the device is running Lollipop or earlier, then the user granted permission at install time, and you’re good to go. But if the device is running Marshmallow, you can’t be so certain. Clever developers can use the support library, though, which will do this check for you. That’s one less line of code for you to add.

Which brings us to step 2: check the permission status. A simple call to checkSelfPermission() (http://goo.gl/T7vE7b ) will let you know if the permission is currently granted. The only scary thing here is that you can’t rely on assumptions here, because even if the user granted the permission in the past, they may have revoked it later on. So with one conditional statement, you’ve completed step 2.

If you don’t have permission, you may need step 3: explain the permission. In some instances, you’ll want to update the UI to clarify what that permission enables and why the feature needs it. This can be as simple as a toast or as complex as the fanciest layout. The coolthing here is that you don’t need to figure out what those moments are. A call to shouldShowRequestPermissionRationale()(http://goo.gl/bFyfVj ) will indicate whether this is one of those clarifying moments. Easy enough, right?

And now, the heart of it-- step 4: request the permission. The requestPermissions() (http://goo.gl/yNuizg ) method will prompt a dialog to the user to get their answer and then trigger your onRequestPermissionResult() callback to handle the response. This is only two lines of code to add. One to make the call, and one to declare the request code, which is indicative of where the user is in your app and what they are trying to do.

Finally, step 5: handle the response. Here is your biggest change, and all it is is overwriting your callback with a switch statement based on that request code. Your request code will help you restore the app to the right state if the permission has been granted. If the user rejected therequest, though, you’ll need to update the UI to disable the feature or indicate that it won’t be available without the permission.

Fig 7. Runtime permissions explained.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

18

Page 19: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.3.5 Runtime permission samplesA very good example for how to deal with run-time permissions is available on the Google samples GitHub repository: https://github.com/googlesamples

Android RuntimePermissions sample: https://github.com/googlesamples/android-RuntimePermissions

Docs: https://developer.android.com/preview/features/runtime-permissions.html

4.4 List with topics you need to understand before next laborationYou must on a basic level be able to:

send and receive SMS managing the permission model in API-23 and above use concurrent programming methods use networking use files use the telephony manager

4.5 Lab Feedback a) Was this a relevant and appropriate lab and what about length etc?

b) What corrections and/or improvements do you suggest for this lab?

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

19

Page 20: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.6 Using a JAR or module library with Android Studio

As with Eclipse you can use a library as source module or as a pre-compiled JAR. Normally however libraries are added via the dependencies section in the module build.gradle file.

If you want to add a pre-compiled JAR library.

1. Goto the project view so you can see the full folder view of your project.

2. If not present create a folder libs in the app folder.

3. Copy the library JAR to the libs directory.

4. Open the projects Module Settings / Project Structure.

5. Goto the Dependencies tab and press the green plus button and select 2. File dependency.

6. Add the library from the libs folder. The dependency should be compiled. Source: http://stackoverflow.com/questions/28472785/compile-provided-apk-android-dependency-scope

Add a module or library as source.

This thread: http://stackoverflow.com/questions/16588064/how-do-i-add-a-library-project-to-the-android-studio or this video: https://www.youtube.com/watch?v=1MyBO9z7ojk deals with how to add a module or library as source. It contains all necessary information.

For reference: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Dependencies-Android-Libraries-and-Multi-project-setup

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

20

Page 21: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

4.7 Using a library in Eclipse (from GitHub)

This is a brief instruction how to use a third-part library from source in Android with Eclipse.In this case we use the OpenCellID Android library found at: https://github.com/msemm/ginstr-GmbH

Note! If you want to use an already compiled JAR library it is simple. Just right-click on the project and open Properties. Select Java Build Path and the Libraries tab. Press the Add JARS… or Add External JARS… button depending on where you put your library. Then the library is more or less ready to use.

You need to install “EGit- Eclipse Git Team Provider” via Help > Eclipse Marketplace first.

1. In eclipse use File > Import and expand Git in the import source tree. Select Projects from Git and press Next.

2. Select Clone URI and press Next.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

21

Page 22: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

3. Get the clone URL from GitHub and paste it in to the URI and press Next.

4. Select branch, usually master and press Next.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

22

Page 23: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

5. Select local destination for the library and press Next.

6. The source is now cloned to you local drive. Select a wizard to import the project to eclipseand press Next.

7. Continue withthis wizard as youwould haveimported anyother project youhave dowloaded and press Next.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

23

Page 24: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

8. Browse to the correct folder and select the library. Then select which of the libraries you want to use and press Finish. Mark ”Copy projects into workspace” if you want a copy which do not change. Let it be unmarked if you want to have the project in synch with GitHub. In this case you need to use the GitHub repository methods as fetch and pull available via the Gitperspective.

9. Examine the properties of the library projects and compile them. It will be libraries, verify by right-click on the project > Properties > Android. It should be marked ”Is library”.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

24

Page 25: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

10. If you want to use the library in your project. Right-click on the project > Properties > Android and press Add...

11. Select the library you want to use in your project and press OK.

12. Press OK again. It will now be included in your project and you can use the functionality.

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

25

Page 26: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

13. You can check that everything is ok by right-click on the project > Properties > Java BuildPath > Libraries and expand the tree.

14. In order to use the library you must check the documentation for available classes and methods. In this case it is found in the projects docs folder. Using the Ctrl-Shift-O command correct imports will be automatically done. For example:

import com.ginstr.android.service.opencellid.upload.OpenCellIDUploadService;

private void OpenCellIDUploadServiceTest()

{OpenCellIDUploadService cellUploadService = null;

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

26

Page 27: 4 Android – Networking, SMS, files and concurrency …index-of.co.uk/Various/lab4_android.pdfLaboration 4, Development of mobile and embedded systems, v16.4 4 Android – Networking,

Laboration 4, Development of mobile and embedded systems, v16.4

try{cellUploadService = new OpenCellIDUploadService(this, "appid");

}catch(Exception e){

Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();e.printStackTrace();

}if(cellUploadService != null) {

cellUploadService.setApiKey("2abcd-...");//... cellUploadService.startService();, stopService, ...

}}

Högskolan Dalarna Telefon: 023-77 80 00Röda vägen 3 Telefax: 023-77 80 50781 88 BORLÄNGE URL: http://www.du.se/

27