Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting.

Similar presentations


Presentation on theme: "Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting."— Presentation transcript:

1 Lecture Series on Android Programming Lecturer: Prof.Luqun Li (liluqun@gmail.com)liluqun@gmail.com Teaching Assistants: Fengyou Sun, Haijun Yang, Ting Sun Chapter 7 Exploring Security and Location-Based Services

2 Shanghai Normal University 2 Contents 1 1Security 2 2 Permissions 3 3 Maps 4 4 Location-based services

3 Shanghai Normal University 3 Android Security Model With respect to deployment, Android appl ications have to be signed with a digital c ertificate in order for you to install them onto a device. With respect to execution, Android runs e ach application within a separate process, each of which has a unique and permane nt user ID (assigned at install time). This places a boundary around the process an d prevents one application from having di rect access to another’s data. Moreover, Android defines a declarative p ermission model that protects sensitive f eatures (such as the contact list).

4 Shanghai Normal University 4 Overview of Security Concepts Android requires that applications be sign ed with a digital certificate. You sign an application with a digital cert ificate. A digital certificate is an artifact t hat contains information about you, such as your company name, address, and so on. Digital certificates are stored in keystores. A keystore contains a list of digital certifi cates, each of which has an alias that yo u can use to refer to it in the keystore.

5 Shanghai Normal University 5 Overview of Security Concepts Signing an Android application requi res three things: a digital certificate, an.apk file, and a utility that knows how to apply a digital signature to t he.apk file.

6 Shanghai Normal University 6 Signing Applications for Deployment 1. To generate a certificate using ke ytool (or a similar tool). 2. Using the jarsigner tool to sign t he.apk file with the generated cer tificate. 3. Aligning portions of your applicati on on memory boundaries for more efficient memory usage when runni ng on a device.

7 Shanghai Normal University 7 Generating a Self-Signed Certificate 1. Create a folder to hold the keys tore, such as c:\android\release\. 2. Open a tools window, and exec ute the keytool utility keytool -genkey -v -keystore "c:\android\rele ase\release.keystore" -alias androidbook -st orepass paxxword -keypass paxxword -keya lg RSA -validity 14000

8 Shanghai Normal University 8 Arguments to the keytool Utility

9 Shanghai Normal University 9 More about The argument alias is a unique na me given to the entry in the keystor e database; you will use this name l ater to refer to the entry Once you have a keystore file for yo ur production certificates, you can r euse this file to add more certificate s. Just use keytool again, and speci fy your existing keystore file.

10 Shanghai Normal University 10 Using Jarsigner to Sign the.apk File Right-clicking an Android project in Eclipse, selecting Android Tools, an d selecting Export Unsigned Applicat ion Package. With the.apk file and the keystore entry, run the jarsigner tool to sign the.apk file jarsigner -keystore "PATH TO YOUR releas e.keystore FILE" -storepass paxxword -keyp ass paxxword "PATH TO YOUR RAW APK FILE" androidbook

11 Shanghai Normal University 11 Using Jarsigner to Sign the.apk File For security reasons, it is safer to le ave off the password arguments to t he command and simply let jarsigne r prompt you as necessary for pass words.

12 Shanghai Normal University 12 Aligning with zipalign Use this command in a tools window zipalign –v 4 infile.apk outfile.apk

13 Shanghai Normal University 13 Using the Export Wizard In Eclipse, you may have noticed a menu choice under Android Tools called Export Signed Application Package. This launches what is called the export wizard, and it does all of the previous ste ps for you, prompting only for the path to your keystore file, key alias, the pass words and the name of your output.apk file. It will even create a new keystore or new key if you need one. You may find it easier to use the wizard, or you may prefer to script the steps you rself to operate on an exported unsigned application package.

14 Shanghai Normal University 14 Installing Apps Open a tools window, and run the a db tool with the install command: adb install "PATH TO APK FILE GOES HER E“

15 Shanghai Normal University 15 Updates of an Application Android tests the certificate’s expiration only at install time. Once your application is installed, it will c ontinue to run even if the certificate expi res. You will not be able to update the applica tion once the certificate expires. The only choice left will be for you to create anoth er application—an application with a diffe rent package name—and sign it with a ne w certificate.

16 Shanghai Normal University 16 Runtime Security Checks Runtime security in Android happens at the proc ess and operation levels. At the process level, Android prevents one appli cation from directly accessing another applicatio n’s data. It does this by running each applicatio n within a different process and under a unique and permanent user ID. At the operational level, Android defines a list of protected features and resources. For your appl ication to access this information, you have to a dd one or more permission requests to your An droidManifest.xml file. You can also define cust om permissions with your application.

17 Shanghai Normal University 17 Contents 1 1Security 2 2 Permissions 3 3 Maps 4 4 Location-based services

18 Shanghai Normal University 18 Declaring and Using Permissions At install time, the APK installer either grants or denies th e requested permissions based on the signature of the.ap k file and/or feedback from the user. Application developers can request permissions by adding entries to the AndroidManifest.xml file. …

19 Shanghai Normal University 19 Declaring and Using Permissions You can either hard-code permissio ns in the AndroidManifest.xml file or use the manifest editor

20 Shanghai Normal University 20 Custom Permissions Android allows you to define custom permissions with your application. To use custom permissions, you firs t declare them in your AndroidMani fest.xml file. Once you’ve defined a permission, y ou can then refer to it as part of yo ur component definition.

21 Shanghai Normal University 21 Strategy Create an application containing an activity that not everyone is allowed to start. To start the activity, a user must ha ve a specific permission. Once you have the application with a privileged activity, you can write a client that knows how to call the a ctivity.

22 Shanghai Normal University 22 The PrivActivity Class package com.cust.perm; public class PrivActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout view = new LinearLayout(this); view.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTEN T)); view.setOrientation(LinearLayout.HORIZONTAL); TextView nameLbl = new TextView(this); nameLbl.setText("Hello from PrivActivity"); view.addView(nameLbl); setContentView(view); }

23 Shanghai Normal University 23 Create a custom permission To create a custom permission usin g the manifest editor

24 Shanghai Normal University 24 Attributes of a Permission

25 Shanghai Normal University 25 Attributes of a Permission

26 Shanghai Normal University 26 The AndroidManifest.xml File <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cust.perm" android:versionCode="1" android:versionName="1.0.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".CustPermMainActivity" android:label="@string/app_name"> <activity android:name="PrivActivity" android:permission="dcm.permission.STARTMYACTIVITY"> <permission android:protectionLevel="normal" android:label="Start My Activity" android:description="@string/startMyActivityDesc" android:name="dcm.permission.STARTMYACTIVITY" />

27 Shanghai Normal University 27 Create the client project Main.xml File for the Client Project <LinearLayout xmlns:android="http://schemas.andro id.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn" android:text="La unch PrivActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick=”doClick” />

28 Shanghai Normal University 28 ClientCustPermMainActivity package com.client.cust.perm; // This file is ClientCustPermMainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class ClientCustPermMainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void doClick(View view) { Intent intent = new Intent(); intent.setClassName("com.cust.perm","com.cust.perm.PrivActivity"); startActivity(intent); }

29 Shanghai Normal University 29 The Client Manifest File <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.client.cust.perm" android:versionCode="1" android:versionName="1.0.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ClientCustPermMainActivity" android:label="@string/app_name">

30 Shanghai Normal University 30 Contents 1 1Security 2 2 Permissions 3 3 Maps 4 4 Location-based services

31 Shanghai Normal University 31 Understanding the Mapping Package The location-based services facility i n Android sits on two pillars: the ma pping and location-based APIs. Mapping in Android boils down to us ing the MapView UI control and th e MapActivity class in addition to t he mapping APIs, which integrate w ith Google Maps.

32 Shanghai Normal University 32 Obtaining a Maps API Key You need two keys: one for developmen t with the emulator and another for prod uction (on devices). To obtain a Maps API key, you need the c ertificate that you’ll use to sign your appl ication (in the case of the emulator, the debug certificate). You’ll get the MD5 fingerprint of your cer tificate, and then you’ll enter it on Googl e’s web site to generate an associated M aps API key.

33 Shanghai Normal University 33 Obtaining a Maps API Key You can find the exact location usin g the Eclipse IDE. From Eclipse’s Pr eferences menu, go to Android ➤ B uild. The debug certificate’s location will be displayed in the Default Deb ug Keystore field.

34 Shanghai Normal University 34 The keytool output for the list option To extract the MD5 finger print, you can run the keytool with the –list option, as shown here: keytool -list -alias androiddebugkey -keystor e "FULL PATH OF YOUR debug.keystore F ILE" -storepass android -keypass android

35 Shanghai Normal University 35 Get MD5 fingerprint Now, paste your certificate’s MD5 fi ngerprint in the appropriate field on this Google site: http://code.google.com/android/maps-api-sig nup.html So too will your development Maps API key. If you change your debug certificate, you’ll n eed to repeat these steps, with the new de b ug certificate, to get a new development Ma ps API key.

36 Shanghai Normal University 36 MapView and MapActivity These two classes is that they have to w ork together. To use a MapView, you need to instantiate it within a MapActivity If you instantiate a MapView using an X ML layout, you need to set the android:a piKey property. If you create a MapView programmatical ly, you have to pass the Maps API key to the MapView constructor.

37 Shanghai Normal University 37 Definition of your map Your application will need permissio n to access the Internet. The definition of your map applicati on needs to reference a mapping lib rary

38 Shanghai Normal University 38 AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidbook" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MapViewDemoActivity" android:label="@string/app_name">

39 Shanghai Normal University 39 XML Layout of the MapView <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/zoomin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:onClick="myClickHandler" android:padding="12px" /> <Button android:id="@+id/zoomout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:onClick="myClickHandler" android:padding="12px" />

40 Shanghai Normal University 40 XML Layout of the MapView <Button android:id="@+id/sat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Satellite" android:onClick="myClickHandler" android:padding="8px" /> <Button android:id="@+id/traffic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Traffic" android:onClick="myClickHandler" android:padding="8px" /> <Button android:id="@+id/normal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Normal" android:onClick="myClickHandler" android:padding="8px" /> <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="true" android:apiKey="YOUR MAPS API KEY GOES HERE" />

41 Shanghai Normal University 41 The MapActivity Extensioned public class MapViewDemoActivity extends MapActivity { private MapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapview); mapView = (MapView)findViewById(R.id.mapview); } public void myClickHandler(View target) { switch(target.getId()) { case R.id.zoomin: mapView.getController().zoomIn(); break; case R.id.zoomout: mapView.getController().zoomOut(); break; case R.id.sat: mapView.setSatellite(true); break;

42 Shanghai Normal University 42 The MapActivity Extensioned case R.id.traffic: mapView.setTraffic(true); break; case R.id.normal: mapView.setSatellite(false); mapView.setTraffic(false); break; } // The following line should not be required but it is, // up through Froyo (Android 2.2) mapView.postInvalidateDelayed(2000); } @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; }

43 Shanghai Normal University 43 View modes Map is the default mode. Satellite mode shows aerial photographs of the map, so you can see the actual top s of buildings, trees, roads, and so on. Traffic mode shows traffic information on the map with colored lines to represent tr affic that is moving well as opposed to tr affic that is backed up. Note that traffic mode is supported on a limited num ber of major highways and roads.

44 Shanghai Normal University 44 Built In Zoom Controls The MapView already has controls that allow you to zoom in and out. All you have to do is turn them on using the setBuiltInZoomControls() method.

45 Shanghai Normal University 45 Zooming Made Easier <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/ android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable=”true” android:apiKey="YOUR MAPS API KEY GOES HERE" /> public class MapViewDemoActivity extends MapActivity { private MapView mapView;

46 Shanghai Normal University 46 Zooming Made Easier @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapview); mapView = (MapView)findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); } @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; }

47 Shanghai Normal University 47 Effect

48 Shanghai Normal University 48 Adding Markers Using Overlays Google Maps provides this facility b y allowing you to add a layer on top of the map. Android provides several classes tha t help you to add layers to a map. The key class for this type of functio nality is Overlay, but you can use a n extension of this class called Itemi zedOverlay.

49 Shanghai Normal University 49 Usage pattern Extend the ItemizedOverlay class and ad d your items—interesting locations—in th e constructor Call the populate() method of ItemizedO verlay To make it all work, the onCreate() meth od of the activity creates the Interesting Locations instance, passing in the Drawa ble that’s used as a default for the marke rs. Then, onCreate() adds the Interesting Locations instance to the overlay collecti on ( mapView.getOverlays().add() ).

50 Shanghai Normal University 50 Effect and Source Code

51 Shanghai Normal University 51 Contents 1 1Security 2 2 Permissions 3 3 Maps 4 4 Location-based services

52 Shanghai Normal University 52 Geocoding Geocoder class take an address and return a latitude/longitu de pair translate a latitude /longitude pair into a list o f addresses

53 Shanghai Normal University 53 Example project To find the address of a location, we call the getFromLocationName() m ethod of Geocoder. The call to getFromLocationName() returns a list of addresses. The sam ple application takes the list of addr esses and processes the first one if any were found.

54 Shanghai Normal University 54 Source code Code Layout Manifest

55 Shanghai Normal University 55 A few points with respect to geocoding First, a returned address is not alwa ys an exact address. Second, better to set the maxResul ts parameter to a value between 1 and 5. Finally, doing the geocoding operati on in a different thread from the UI thread.

56 Shanghai Normal University 56 Effect with background thread

57 Shanghai Normal University 57 LocationManager Central component of the location fr amework You request an instance from the sy stem by calling getSystemService(C ontext.LOCATION_SERVICE)

58 Shanghai Normal University 58 LocationManager Query for the list of all LocationProviders for the last known user location. Register/unregister for periodic updates of the user's current location from a locat ion provider (specified either by criteria o r name). Register/unregister for a given Intent to be fired if the device comes within a give n proximity (specified by radius in meter s) of a given lat/long.

59 Shanghai Normal University 59 LocationProvider The LocationManager service provides g eographical location details by using loca tion providers. GPS providers use a Global Positioning System to o btain location information. Network providers use cell-phone towers or Wi-Fi networks to obtain location information. The passive provider is like a location update sniffe r, and it passes to your application location updates that are requested by other applications, without you r application having to specifically request any locati on updates. Of course, if no one else is requesting l ocation updates, you won’t get any either.

60 Shanghai Normal University 60 Enable Location Providers To get a location service turned on, t he user must do that from within t he Settings screens of their device.

61 Shanghai Normal University 61 Sending Location Updates One of the primary uses of the LocationM anager service is to receive notifications of the device’s location. You can register a listener to receive loca tion-update events To register a listener, you call the reque stLocationUpdates() method, passing t he provider type as one of the parameter s. When the location changes, the Location Manager calls the onLocationChanged() method of the listener with the new Loca tion

62 Shanghai Normal University 62 To test this in the emulator

63 Shanghai Normal University 63 Effect and Source Code

64 Shanghai Normal University 64 Summary Digital certificates and their use in s igning Android applications Permissions that applications can de clare and use MapView and MapActivity The LocationManager service Using LocationOverlay

65 Shanghai Normal University 65 Interview Questions 1. Which tool is used to create or view a digital certificate? 2. What must happen first before an application can grant a URI perm ission to another activity? 3. How is a Maps API key related t o your keystore certificate? 4. Name some of the methods that you can call on a Location object.


Download ppt "Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting."

Similar presentations


Ads by Google