GPS and MapView. First In the emulator, set the time zone to something (e.g., east coast) and check that the time is correct. Otherwise, the gps emulator.

Slides:



Advertisements
Similar presentations
Using T4Eclipse tool to Analyze Eclipse UI For t4eclipse version Ben Xu July 17,2010.
Advertisements

Android Application Development Tutorial. Topics Lecture 4 Overview Overview of Sensors Programming Tutorial 1: Tracking location with GPS and Google.
Google APIs & Location Based Applications -Krishna Achanta
Bruce Scharlau, University of Aberdeen, 2010 Android and Location Mobile Computing Unless otherwise stated, images are from android sdk.
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Google MAP KEY. JDK 1.6 버전 : keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android JDK 1.7 이후 버전 : keytool.
Cosc 5/4730 Android Maps v2. Maps V1 and V2 In March 2013 google removed the ability to get a map key for version 1. Version 2 had been introduced in.
Programming with Android: SDK install and initial setup Luca Bedogni Marco Di Felice Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna.
CS378 - Mobile Computing Maps. Using Google Maps Like other web services requires an API key from Google ons/google-apis/mapkey.html.
Chapter 11: Discover! Incorporating Google Maps
Get android development environment running. Install – Get and install JDK 5 or 6 (see link in the.
Android: Hello World Frank Xu Gannon University. Steps Configuration ▫Android SDK ▫Android Development Tools (ADT)  Eclipse plug-in ▫Android SDK and.
The Java Crypto API ICW Lecture 3 Tom Chothia. Reminder of Last Time: Your programs defines “Classes”. Each class defines “Objects”. An Object is defined.
If your Java applet does not run Prashanth Sanagavarapu.
Update the PATH variable Trying to run the command: “javac Ex1.java” you’ve may encountered the error: “javac is not recognized as internal or external.
UFCFX5-15-3Mobile Device Development Android Development Environments and Windows.
SET UP COMPUTER ** PLEASE BE AWARE SCREENSHOTS MAY NOT MATCH **
Virtual Reality Course Slide  NTU Mobile HCI Lab, Mike Chen   Android Developers 
Computers as an Expressive Medium Lab 8: jar signing, debugging Mayhew Seavey.
Getting Started with Android Programming Note: if you have already installed android development tools, please check that you have the same version as.
Android Tutorial Larry Walters OOSE Fall References This tutorial is a brief overview of some major concepts…Android is much richer and more complex.
SEEM4570: XAMPP, Eclipse, Summary of Html Kangfei Zhao Room 711,ERB
Android Programming Day best Android Apps Lzo&feature=fvwrel.
CS378 - Mobile Computing Maps. Using Google Maps Content on using Google Maps inside your app Alternatives: Open Street Maps –
Sayed Ahmed BSc. Eng. In Computer Sc. and Eng. (BUET), Bangladesh MSc., Computer Science, Canada President/Chief Architect/Lead Developer Justetc (Just.
Final Thoughts and Discussion. Online Resources developer.android.com code.google.com/p/apps-for-android/ stackoverflow.com Chris Murphy:
Google Maps Android API v2 吳俊興 國立高雄大學 資訊工程學系 CSF645 – Mobile Computing 行動計算
Chapter 12: Finale! Publishing Your Android App. Objectives In this chapter, you learn to: Understand Google Play Target various device configurations.
1 Mobile Computing Set Up Copyright 2015 by Janson Industries.
Mobile Programming Lecture 16 The Facebook API. Agenda The Setup Hello, Facebook User Facebook Permissions Access Token Logging Out Graph API.
PARSING FACEBOOK DATA FOR ANDROID 1. Step by Step  Import Android SDK  Get the hash key  Create a new app  Create a new project in Eclipse 
Ali Shahrokni Application Components Activities Services Content providers Broadcast receivers.
Geo CE-XM ch 4 Edited 10/14/05 1 The XM is the newest of the rovers, and unlike other units, it comes with software installed on the unit as well as using.
DUE Introduction to the Android Platform Working Connections 2011.
Chapter 12: Finale! Publishing Your Android App
Presented By: Muhammad Tariq Software Engineer Android Training course.
How to publish your app 1 CS440. Step 1: Remove any debug logging  Good practice: comment out any debug logging  Why? CS440 2.
Open a editor Write/Type the program Save the program with “.c” extension Compile the program (alt + F9) Run/Execute the program (ctrl + F9) Check the.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Introduction to Android (Part.
Android Development Environment Environment/tools Windows Eclipse IDE for Java Developers (v3.5 Galileo) Java Platform (JDK 6 Update 18) Android.
Setting Up Eclipse. What is Eclipse? Eclipse is a free, downloadable software that allows us to create, compile, and run JAVA programs.
First Venture into the Android World Chapter 1 Part 2.
Installing TerraSync The TerraSync CD should have been in the same package as the Juno and Pathfinder Office. When you put the TerraSync CD into the computer,
TIBCO BusinessWorks.  Generating the key   You will have to create a certificate as you own the server.  The ‘Keytool’ is a utility provided in the.
Java On the ENB 116 Computers The JDK is now available on the ENB 116 computers. You can use a classroom computer rather than your own laptop or CIRCE.
Time to apply stuff… Faculty of Mathematics and Physics Charles University in Prague 5 th October 2015 Workshop 1 – Java Wrestling.
Eclipse Basics Create projects Debug Import/Export: s/import_export/
Cosc 5/4735 YouTube API. YouTube The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications.
LAB#8 PKI & DIGITAL CERTIFICATE CPIT 425. Public Key Infrastructure PKI 2  Public key infrastructure is the term used to describe the laws, policies,
GOOGLE PLAY By William Cook April 14, GOOGLE PLAY Marketplace for apps for android Androids “app store” You must make an account on the developer.
GPS and MapView. First In the emulator, set the time zone to something (e.g., east coast) and check that the time is correct. Otherwise, the gps emulator.
CS371m - Mobile Computing Maps. Using Google Maps Content on using Google Maps inside your app Alternatives Exist: – Open Street Maps –
Guide To Develop Mobile Apps With Titanium. Agenda Overview Installation of Platform SDKs Pros of Appcelerator Titanium Cons of Appcelerator Titanium.
Day 1 Session 2. Setup & Installation
Mobile Device Development
Android Application Maps 1.
Obtaining the Required Tools
Outline Install Java Change Security Files in Java
1. Open any Office 2016 app, such as Word, and create a new document.
The GoogleMap API By Cody Littley.
Publishing & Deployment
Find your friend – An Android application
1. Open Visual Studio 2008.
Run Java file with Window cmd
JCreator Settings Only
SSL certificates TIBCO BusinessWorks.
Working with Libraries
Review of Previous Lesson
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

GPS and MapView

First In the emulator, set the time zone to something (e.g., east coast) and check that the time is correct. Otherwise, the gps emulator might not work correctly

plan Show maps Show markers on map Get gps locations Put marker of current location

Get API key Get google maps api key The api key allows you to use the google api The key must be the same as the app key – The eclipse plug in includes a debug key. But when selling apps, you should use your key – For now, we will use the debug key Get the debug certificate – Find where the certificate is Eclipse: menu window->preferences -> android -> build. See field “Default debug keystore:” E.g., c:\documents and settings\stephan\.android\debug.keystore – Get certificate Open cmd shell Go to java jdk directory – E.g., c:\program files\java\jdk1.6.0_18\bin Run – keytool –list –alias androiddebugkey –keystore LOCATION_OF_KEYSTORE –storepass android -keypass android E.g., – keytool –list –alias androiddebugkey –keystore “c:\documents and settings\stephan\.android\debug.keystore“ – storepass android -keypass android – (for some reason, cutting the above into the cmd shell does nto work. It must be typed) The certificate is given: 61:AB:CD:….. 41:F4:A5:79:A7:F8:14:15:D4:00:37:CF:23:9A:40:D2 Get key from google – Go to – Paste certificate into window – Read and agree to conditions – Select ok – Login with gmail account – Get key If this gives error invalid key, then rerun keytool …. –v <<< add –v to end of command

Make view Make new app called ShowMap – Be sure that the app uses Google APIs Google apis extends android sdk and includes some libraries and services, e.g., maps – ShowMap – Open res/layout/main.xml – Go to layout view – drag toggle button to view. Highlight button and Change Id to streetOrSatellite Remove text Add text on “Street“ Add text off “Satellite” save – Add map view Open main.xml view (not layout view) After ToggleButton but before, add (note that the key is show here) <com.google.android.maps.MapView android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="0v-E_CPfInucTQUyOhRT_x__fBXwj0YQ6n_ZA8A" android:clickable="true"/> Save Check out layout view. – The map view box is shown – Properties are also show

Set permissions and library Open manifest Set permissions – To use the google maps, the internet is needed – Go to permissions tab – Create a new “User permission” – Set Name to android.permission.INTERNET We’ll need other permissions to use location info – Add “User permission” – Set Name to android.permission.ACCESS_COARSE_LOCATION – Add “User permission” – Set Name to android.permission.ACCESS_FINE_LOCATION – Add “User permission” – Set Name to android.permission.ACCESS_MOCK_LOCATION (for setting locations for testing. Will not use in this exercise, but I add it just in case I want to use it later) Add android maps library – Go to Applications tab – Go to application nodes – Add “Uses Library” – Name = com.google.android.maps This should be an option in a drop down list. – If not, then you are not using the google api. Recreate the project but use the google api

Change java code to show map Open ShowMap.java Make activity into MapActivity – Change “extends Activity” to “extends MapActivity” – MapActivity will be underlined in red. Hoover the mouse over MapActivity. Drop down list appears. Select Import – MapActivity requires isRouteDisplayed be implemented Eclipse will ask to do this automatically ShowMap is underlined in red – Hover mouse over ShowMap – Select option to add unimplemented methods – isRouteDisplayed should appear If eclipse instead only gives the option to create MapActivity, then you did not use a google API. If not, then you are not using the google api. Recreate the project but use the google protected boolean isRouteDisplayed() { return false; } Run

Add zoom + panning controls (Panning and zoom are implemented by default. But zoom is needed for the emulator) Panning – Note: in main.xml we added android:clickable="true“ – This allows pan Zooming – Make reference to MapView object. Add private MapView mapView; As a class attribute near the top of ShowMap class – Set mapView In onCreate add mapView = (MapView)findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); Run

Add toggle for satellite and street view Get reference to toogle button – In ShowMap.java – Just after public class ShowMap extends MapActivity, add MapView mapView = null; – At the end of onCreate, add mapView = (MapView)findViewById(R.id.mapview); final ToggleButton streetViewBtn = (ToggleButton)findViewById(R.id.streetOrSatellite); After this, set ClickListener streetViewBtn.setOnClickListener(new OnClickListener() public void onClick(View view) { if (streetViewBtn.isChecked()) { mapView.setSatellite(true); } else { mapView.setSatellite(false); } });

Import marker One can draw the marker in the program, or use a drawable resource. We’ll use a drawable resource Import marker – – Right click on image and save as c:\temp\orange_sel_marker.png – Open file explorer and open c:\temp – Drag orange_sel_marker.png to res/drawable-mdpi if asked, select copy Add maker object – In ShowMap.java, after streetViewBtn.setOnClickListener – Add Drawable marker = getResources().getDrawable(R.drawable.orange_sel_marker); marker.setBounds(0,0,marker.getIntrinsicWidth(), marker.getIntrinsicHeight());

Add marker to map Marker can take several forms. We will use ItemizedOverlay. These can represent a list of markers However, we must make a class that extends ItemizedOverlay Near the top ShowMap class definition, add – Places places; // Places is our class that extends ItemizedOverlay. This is defined below

Define class Places class Places extends ItemizedOverlay { private List locations = new ArrayList (); private Drawable marker; public Places(Drawable marker) { super(marker); this.marker = marker; GeoPoint UD = new GeoPoint((int)( * ), (int)( * )); GeoPoint home = new GeoPoint((int)( * ), (int)( * )); locations.add(new OverlayItem(UD, "Evans Hall", "EvansHall")); locations.add(new OverlayItem(home, "Home", "Home")); populate(); public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); boundCenterBottom(marker); protected OverlayItem createItem(int i) { return locations.get(i); public int size() { return locations.size(); } After onCreate is complete, add

Attach Places to the map places = new Places(marker); mapView.getOverlays().add(places); At the end of onCreate, add run

Play with adding locations Add another toggle button – Go to main.xml (graphical layout) – Drag a toggle button next to a street/satellite button You can’t drag it next to it, only about or below. So, drag it below – Change id to switchPlaces Right click, select edit id – We want to put the new toggle button on the right of the street/satellite button. To so this, we need to add a layout – In palettes, open layouts Layouts control … how things are laid out – Drag LinearLayout (horizontal) to near the street/satellite button – Open the main.xml (xml view) – Let’s understand what is there Two toggle buttons – <ToggleButton – switchPlaces Two linear layouts – At the top, <LinearLayout … “vertical” – In the middle <LinearLayout – the one in the middle is the default of horizontal layout – Note the first one has a at the bottom of the xml – The for the horizontal one is just after the – Cut the text for the two toggle buttons so they are between the and – save, check out graphical view – Now buttons are next to each other, laid out horizontally

Play with adding locations Go back to ShowMapActivity.java At the end of onCreate, add – final ToggleButton switchBtn = (ToggleButton) findViewById(R.id.switchPlaces); – switchBtn.setOnClickListener(new OnClickListener(){ – public void onClick(View v) { if (switchBtn.isChecked()) { – places.resetPlaces(true); } else { – places.resetPlaces(false); } – }} ); We need to make the restPlaces function A bit below Class Places extends ItemizedOverlay, add – public void resetPlaces(boolean which) { – if (which) { locations.clear(); GeoPoint UD = new GeoPoint((int)( * ), (int)( * )); GeoPoint home = new GeoPoint((int)( * ), (int)( * )); locations.add(new OverlayItem(UD, "Evans Hall", "EvansHall")); locations.add(new OverlayItem(home, "Home", "Home")); – } else { locations.clear(); GeoPoint UD = new GeoPoint((int)( * ), (int)( * )); GeoPoint home = new GeoPoint((int)( * ), (int)( * )); locations.add(new OverlayItem(UD, "Evans Hall", "EvansHall")); locations.add(new OverlayItem(home, "Home", "Home")); – } – populate(); // set up itemizedoverlay things – mapView.invalidate(); // forces map to redraw (whenever you change a view, you need to redraw it. invalidate is one way to get it redrawn) – } Run it Try with populate commented out. Try with invaliate commented out… We need them both

Draw line between markers Drawing – see Graphics with Canvas for more on graphics We will make another overlay for the lines – We will make a class that overrides overlay and override draw Add class to ShowMapActivity. At the end of ShowMapActivity.java (but before }), add class Connectors extends Overlay{ Paint paint; Path path; public Connectors(){ } public void draw(Canvas canvas, MapView mapv, boolean shadow){ super.draw(canvas, mapv, shadow); } Overlay.draw has argument canvas, which we can use drawPath as in “Graphics with Canvas”

Now add to Connectors.onDraw function Set the paint used to draw In constructor (public Connectors() { }), add paint = new Paint(); paint.setDither(true); paint.setColor(Color.RED); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(8);

Now add to Connector.onDraw function Will draw a path between the points in the itemizedOverlay Get locations from other overlay In public void draw(…), add – GeoPoint gP1 = places.createItem(0).getPoint(); – GeoPoint gP2 = places.createItem(1).getPoint(); – // obviously, this could be a loop for (int i=0; i<places.size(); i++) { …} Problem: – locations are in GeoCorrdinates, and we need screen coordinates – Projection can convert between the two coordinates Point p1 = new Point(); mapView.getProjection().toPixels(gP1, p1); // p1 is the screen coordinates of gp1 Point p2 = new Point(); mapView.getProjection().toPixels(gP2, p2); Now make path object Path path = new Path(); path.moveTo(p2.x, p2.y); path.lineTo(p1.x,p1.y); Draw canvas.drawPath(path, paint); Call connector – Make connector object – At the top of ShowMapActivity, add Connectors connectors = null; – Near the top of onCreate, add connectors = new Connectors(); – In Place.draw, add connectors.draw(canvas, mapView, shadow); Save & Run

Add Localization (e.g., GPS) Recall that we have already added permissions Request localization service. In onCreate, just before places = new …, add Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.NO_REQUIREMENT); Next, get service At the top of ShowMapActivity, add LocationManager locationManager = null; After criteria …, add locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); String locInfo = String.format("Initial loc = (%f, (%f meters up)", location.getLatitude(), location.getLongitude(), location.getAltitude() ); Toast.makeText(this, locInfo, Toast.LENGTH_SHORT).show(); Log.e("DEBUGINFO",locInfo); Unfortunately, the above might crash because it takes too long to get a location or because getLastKnownLocation returns null locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); if (location!=null) { String locInfo = String.format("Initial loc = (%f, (%f meters up)", location.getLatitude(), location.getLongitude(), location.getAltitude() ); Toast.makeText(this, locInfo, Toast.LENGTH_SHORT).show(); Log.e("DEBUGINFO",locInfo); } else { Toast.makeText(this, new String("locaiton is null"), Toast.LENGTH_SHORT).show(); }

Fix location info Toast is too fast Use TextView to display location Go to main.xml Select TextView box Change id Instead of toast… add TextView textView = (TextView)findViewById(R.id.headertext); textView.setText(locInfo); Run

Get location updates For this, we need to define a location listener, which requires making a class that implements LocationListener. After onCreate is defined, add class MyLocationListener implements LocationListener { public void onLocationChanged(Location location) { String locInfo = String.format("Current loc = (%f, (%f meters up)", location.getLatitude(), location.getLongitude(), location.getAltitude() ); Toast.makeText(ShowMapActivity.this, locInfo, Toast.LENGTH_SHORT).show(); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) { } } Set the an object of type MyLocationListener to be the listener. After textView.setText(locInfo); add textView.setText("waiting for location"); locationManager.requestLocationUpdates(provider, 1000, 0, new MyLocationListener()); Min time between updates in millsec Min distance in meters between updates RUN

Setting location in the emulator Be sure that the time zone in the emulated phone was set (it is set in settings) In eclipse, in the upper right, select DDMS On the left, select the emulator that is running Below, note “Emulator control” – If emulator control is not there, meun -> window-> show view - > other -> android -> emulator control In emulator control, scroll to Location Control Select Manual tab Enter various values and select send Try coordinates around DE, lat= lon=

Put a marker on current location Our Places class has a list of marker locations. We need to add a marker whenever the location listener gets a new location Make a Places function called public void update(Location currentLocation), as follows. At the end of the class Places definition, add public void update(Location currentLocation) { locations.remove(locations.size()-1); // remove oldest GeoPoint current = new GeoPoint((int)(currentLocation.getLatitude()* ), (int)(currentLocation.getLongitude()* )); locations.add(0,new OverlayItem(current, "current", "current")); populate(); ShowMapActivity.this.mapView.postInvalidate(); setLastFocusedIndex(-1); } At the end of MyLocationListener.onLocationChanged, add ShowMapActivity.this.places.update(location); Run and change location with the ddms

Center map around current location At the end of Places.update, add MapController mapControl = ShowMapActivity.this.mapView.getController(); mapControl.animateTo(current);

Proximity Alert When the user gets near a location, get an alert A more useful way is to use services. We will do that later. Tasks – Set alert Tell LocationManager – Receive alert Receiver is a separate class BroadcastReceiver

Set up alert At the end of ShowMapActivity, add private static final String PROX_ALERT_INTENT = "edu.udel.eleg454.ShowMaps.ProximityAlert"; private void addProximityAlert(double latitude, double longitude) { Intent intent = new Intent(PROX_ALERT_INTENT); PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0); locationManager.addProximityAlert( latitude, // the latitude of the central point of the alert region longitude, // the longitude of the central point of the alert region 1000, // the radius of the central point of the alert region, in meters -1, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected ); IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT); registerReceiver(new ProximityIntentReceiver(), filter); } Call addProximityAlert after location manager is set up, e.g., at the end of onCreate, add – addProximityAlert( , );

Receive alert Make new class in ShowMapActivity. At the end of ShowMapActivity (but before }), add public class ProximityIntentReceiver extends BroadcastReceiver public void onReceive(Context context, Intent intent) { – // TODO Auto-generated method stub – Log.e("show","got message"); – String key = LocationManager.KEY_PROXIMITY_ENTERING; – Boolean entering = intent.getBooleanExtra(key, false); – if (entering) { Log.d("ShowMapActivity", "ENTERING"); Toast.makeText(context, new String("entering"), Toast.LENGTH_SHORT).show(); – } else { Log.d("ShowMapActivity", "EXITING"); Toast.makeText(context, new String("exiting"), Toast.LENGTH_SHORT).show(); – } } Save+run In the ddms, set long= , lat= , then try lat= Check if toast appears. Also check in log