Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture Series on Android Programming Chapter 7 Exploring Security and Location-Based Services Lecturer: Prof.Luqun Li ([email protected]) Teaching Assistants: Fengyou Sun, Haijun Yang, Ting Sun Contents 2 1 Security 2 Permissions 3 Maps 4 Location-based services Shanghai Normal University 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). 3 Shanghai Normal University Overview of Security Concepts Android requires that applications be sign ed with a digital certificate. You sign an application with a digital certi ficate. A digital certificate is an artifact th at 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. 4 Shanghai Normal University 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. 5 Shanghai Normal University 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. 6 Shanghai Normal University 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 execu te 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 7 Shanghai Normal University Arguments to the keytool Utility 8 Shanghai Normal University 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. 9 Shanghai Normal University 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 release. keystore FILE" -storepass paxxword -keypas s paxxword "PATH TO YOUR RAW APK FIL E" androidbook 10 Shanghai Normal University 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. 11 Shanghai Normal University Aligning with zipalign Use this command in a tools window zipalign –v 4 infile.apk outfile.apk 12 Shanghai Normal University 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 passw ords and the name of your output .apk fi le. It will even create a new keystore or n ew 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. 13 Shanghai Normal University 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“ 14 Shanghai Normal University Updates of an Application Android tests the certificate’s expiration o nly 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. 15 Shanghai Normal University 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. 16 Shanghai Normal University Contents 17 1 Security 2 Permissions 3 Maps 4 Location-based services Shanghai Normal University 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. <manifest … > <application> … </application> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.READ_CON TACTS"/> <uses-permission android:name="android.permission.READ_CAL ENDAR" /> </manifest> 18 Shanghai Normal University Declaring and Using Permissions You can either hard-code permissio ns in the AndroidManifest.xml file or use the manifest editor 19 Shanghai Normal University Custom Permissions Android allows you to define custom permissions with your application. To use custom permissions, you first declare them in your AndroidManife st.xml file. Once you’ve defined a permission, y ou can then refer to it as part of yo ur component definition. 20 Shanghai Normal University 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. 21 Shanghai Normal University 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); } 22 } setContentView(view); Shanghai Normal University Create a custom permission To create a custom permission using the manifest editor 23 Shanghai Normal University Attributes of a Permission 24 Shanghai Normal University Attributes of a Permission 25 Shanghai Normal University The AndroidManifest.xml File <?xml version="1.0" encoding="utf-8"?> <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"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="PrivActivity" android:permission="dcm.permission.STARTMYACTIVITY"> <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> </activity> </application> <permission android:protectionLevel="normal" android:label="Start My Activity" android:description="@string/startMyActivityDesc" android:name="dcm.permission.STARTMYACTIVITY" /> <uses-sdk android:minSdkVersion="4" /> </manifest> 26 Shanghai Normal University Create the client project Main.xml File for the Client Project <?xml version="1.0" encoding="utf-8"?> <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” /> </LinearLayout> 27 Shanghai Normal University ClientCustPermMainActivity package com.client.cust.perm; // This file is ClientCustPermMainActivity.java import import import import android.app.Activity; android.content.Intent; android.os.Bundle; android.view.View; public class ClientCustPermMainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 28 public void doClick(View view) { Intent intent = new Intent(); intent.setClassName("com.cust.perm","com.cust.perm.PrivActivity"); startActivity(intent); } Shanghai Normal University The Client Manifest File <?xml version="1.0" encoding="utf-8"?> <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"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="dcm.permission.STARTMYACTIVITY" /> <uses-sdk android:minSdkVersion="4" /> </manifest> 29 Shanghai Normal University Contents 30 1 Security 2 Permissions 3 Maps 4 Location-based services Shanghai Normal University 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. 31 Shanghai Normal University Obtaining a Maps API Key You need two keys: one for development with the emulator and another for produc tion (on devices). To obtain a Maps API key, you need the c ertificate that you’ll use to sign your appli cation (in the case of the emulator, the d ebug certificate). You’ll get the MD5 fingerprint of your cert ificate, and then you’ll enter it on Google’ s web site to generate an associated Map s API key. 32 Shanghai Normal University 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. 33 Shanghai Normal University 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 FI LE" -storepass android -keypass android 34 Shanghai Normal University 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. 35 Shanghai Normal University MapView and MapActivity These two classes is that they have to wo rk 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. 36 Shanghai Normal University Definition of your map Your application will need permissio n to access the Internet. <uses-permission android:name="android.p ermission.INTERNET" /> The definition of your map applicati on needs to reference a mapping lib rary <uses-library android:name="com.google.a ndroid.maps" /> 37 Shanghai Normal University AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <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"> <uses-library android:name="com.google.android.maps" /> <activity android:name=".MapViewDemoActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"/> <uses-sdk android:minSdkVersion="4" /> </manifest> 38 Shanghai Normal University XML Layout of the MapView <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/mapview.xml --> <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" /> 39 Shanghai Normal University 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" /> </LinearLayout> <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" /> </LinearLayout> 40 Shanghai Normal University 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; 41 Shanghai Normal University 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; } } 42 @Override protected boolean isRouteDisplayed() { return false; } Shanghai Normal University 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. 43 Shanghai Normal University 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. 44 Shanghai Normal University Zooming Made Easier <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/mapview.xml --> <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" /> </RelativeLayout> public class MapViewDemoActivity extends MapActivity { private MapView mapView; 45 Shanghai Normal University 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; } } 46 @Override protected boolean isRouteDisplayed() { return false; } Shanghai Normal University Effect 47 Shanghai Normal University 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 an extension of this class called Itemiz edOverlay . 48 Shanghai Normal University 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 collectio n ( mapView.getOverlays().add() ). 49 Shanghai Normal University Effect and Source Code 50 Shanghai Normal University Contents 51 1 Security 2 Permissions 3 Maps 4 Location-based services Shanghai Normal University Geocoding Geocoder class take an address and return a latitude/longitu de pair translate a latitude /longitude pair into a list o f addresses 52 Shanghai Normal University 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. 53 Shanghai Normal University Source code Code Layout Manifest 54 Shanghai Normal University 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. 55 Shanghai Normal University Effect with background thread 56 Shanghai Normal University LocationManager Central component of the location fr amework You request an instance from the sy stem by calling getSystemService(C ontext.LOCATION_SERVICE) 57 Shanghai Normal University 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. 58 Shanghai Normal University 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. 59 Shanghai Normal University 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. 60 Shanghai Normal University 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 reques tLocationUpdates() method, passing th e provider type as one of the parameters. When the location changes, the Location Manager calls the onLocationChanged() method of the listener with the new Loca tion 61 Shanghai Normal University To test this in the emulator 62 Shanghai Normal University Effect and Source Code 63 Shanghai Normal University 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 64 Shanghai Normal University 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. 65 Shanghai Normal University