New OpenDocument Text
-
Upload
cristiananegr -
Category
Documents
-
view
12 -
download
2
description
Transcript of New OpenDocument Text
coursera-android-location-lab
coursera-android-location-lab/Skeleton/src/course/labs/locationlab/MockLocationProvider.javaKyle Jorgensenkjorg50on 20 Apr 2014initial commit1contributorRawBlameHistory47 lines (34 sloc)1.346 kbpackage course.labs.locationlab;
// Adapted from code found at:
// http://mobiarch.wordpress.com/2012/07/17/testing-with-mock-location-data-in-android/
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.SystemClock;
public class MockLocationProvider {
private String mProviderName;
private LocationManager mLocationManager;
private static float mockAccuracy = 5;
public MockLocationProvider(String name, Context ctx) {
this.mProviderName = name;
mLocationManager = (LocationManager) ctx
.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.addTestProvider(mProviderName, false, false, false,
false, true, true, true, 0, 5);
mLocationManager.setTestProviderEnabled(mProviderName, true);
}
public void pushLocation(double lat, double lon) {
Location mockLocation = new Location(mProviderName);
mockLocation.setLatitude(lat);
mockLocation.setLongitude(lon);
mockLocation.setAltitude(0);
mockLocation.setTime(System.currentTimeMillis());
mockLocation
.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
mockLocation.setAccuracy(mockAccuracy);
mLocationManager.setTestProviderLocation(mProviderName, mockLocation);
}
public void shutdown() {
mLocationManager.removeTestProvider(mProviderName);
}
}
coursera-android-location-lab/Skeleton/src/course/labs/locationlab/PlaceDownloaderTask.javaKyle Jorgensenkjorg50on 20 Apr 2014updaed geoname ID1contributorRawBlameHistory229 lines (178 sloc)5.856 kbpackage course.labs.locationlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.util.Log;
public class PlaceDownloaderTask extends AsyncTask {
// Change to false if you don't have network access
private static final boolean HAS_NETWORK = true;
// DONE - put your www.geonames.org account name here.
private static String USERNAME = "kjorg50";
private HttpURLConnection mHttpUrl;
private WeakReference mParent;
private static Bitmap mStubBitmap;
private static Location mockLoc1 = new Location(LocationManager.NETWORK_PROVIDER);
private static Location mockLoc2 = new Location(LocationManager.NETWORK_PROVIDER);
public PlaceDownloaderTask(PlaceViewActivity parent) {
super();
mParent = new WeakReference(parent);
if (!HAS_NETWORK) {
mStubBitmap = BitmapFactory.decodeResource(parent.getResources(),R.drawable.stub);
mockLoc1.setLatitude(37.422);
mockLoc1.setLongitude(-122.084);
mockLoc2.setLatitude(38.996667);
mockLoc2.setLongitude(-76.9275);
}
}
@Override
protected PlaceRecord doInBackground(Location... location) {
PlaceRecord place = null;
if (HAS_NETWORK) {
place = getPlaceFromURL(generateURL(USERNAME, location[0]));
if ("" != place.getCountryName()) {
place.setLocation(location[0]);
place.setFlagBitmap(getFlagFromURL(place.getFlagUrl()));
} else {
place = null;
}
} else {
place = new PlaceRecord(location[0]);
if (location[0].distanceTo(mockLoc1) < 100) {
place.setCountryName("United States");
place.setPlace("The Greenhouse");
place.setFlagBitmap(mStubBitmap);
} else {
place.setCountryName("United States");
place.setPlace("Berwyn");
place.setFlagBitmap(mStubBitmap);
}
}
return place;
}
@Override
protected void onPostExecute(PlaceRecord result) {
if (null != result && null != mParent.get()) {
mParent.get().addNewPlace(result);
}
}
private PlaceRecord getPlaceFromURL(String... params) {
String result = null;
BufferedReader in = null;
try {
URL url = new URL(params[0]);
mHttpUrl = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(
mHttpUrl.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
mHttpUrl.disconnect();
}
return placeDataFromXml(result);
}
private Bitmap getFlagFromURL(String flagUrl) {
InputStream in = null;
Log.i("temp", flagUrl);
try {
URL url = new URL(flagUrl);
mHttpUrl = (HttpURLConnection) url.openConnection();
in = mHttpUrl.getInputStream();
return BitmapFactory.decodeStream(in);
} catch (MalformedURLException e) {
Log.e("DEBUG", e.toString());
} catch (IOException e) {
Log.e("DEBUG", e.toString());
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
mHttpUrl.disconnect();
}
return BitmapFactory.decodeResource(mParent.get().getResources(),
R.drawable.stub);
}
private static PlaceRecord placeDataFromXml(String xmlString) {
DocumentBuilder builder;
String countryName = "";
String countryCode = "";
String placeName = "";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(
xmlString)));
NodeList list = document.getDocumentElement().getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node curr = list.item(i);
NodeList list2 = curr.getChildNodes();
for (int j = 0; j < list2.getLength(); j++) {
Node curr2 = list2.item(j);
if (curr2.getNodeName() != null) {
if (curr2.getNodeName().equals("countryName")) {
countryName = curr2.getTextContent();
} else if (curr2.getNodeName().equals("countryCode")) {
countryCode = curr2.getTextContent();
} else if (curr2.getNodeName().equals("name")) {
placeName = curr2.getTextContent();
}
}
}
}
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new PlaceRecord(generateFlagURL(countryCode.toLowerCase()),
countryName, placeName);
}
private static String generateURL(String username, Location location) {
return "http://www.geonames.org/findNearbyPlaceName?username="
+ username + "&style=full&lat=" + location.getLatitude()
+ "&lng=" + location.getLongitude();
}
private static String generateFlagURL(String countryCode) {
return "http://www.geonames.org/flags/x/" + countryCode + ".gif";
}
}
coursera-android-location-lab/Skeleton/src/course/labs/locationlab/PlaceViewActivity.javaKyle Jorgensenkjorg50on 20 Apr 2014remove TODOs1contributorRawBlameHistory243 lines (188 sloc)7.046 kbpackage course.labs.locationlab;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PlaceViewActivity extends ListActivity implements LocationListener {
private static final long FIVE_MINS = 5 * 60 * 1000;
private static String TAG = "Lab-Location";
private Location mLastLocationReading;
private PlaceViewAdapter mAdapter;
// default minimum time between new readings
private long mMinTime = 5000;
// default minimum distance between old and new readings.
private float mMinDistance = 1000.0f;
private LocationManager mLocationManager;
// A fake location provider used for testing
private MockLocationProvider mMockLocationProvider;
private TextView mFooterView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// DONE - Set up the app's user interface
// This class is a ListActivity, so it has its own ListView
// ListView's adapter should be a PlaceViewAdapter
mAdapter = new PlaceViewAdapter(getApplicationContext());
// from UI lab...
// Put divider between ToDoItems and FooterView
getListView().setFooterDividersEnabled(true);
// DONE - add a footerView to the ListView
// You can use footer_view.xml to define the footer
// 1. get a layout inflater
// 2. call the inflate method, with the id of the footer view resource
// 3. cast it as a TextView
mFooterView = (TextView) this.getLayoutInflater().inflate(R.layout.footer_view, null);
// adds it to the ListView
getListView().addFooterView(mFooterView);
// enable it only if there is a location
mFooterView.setEnabled(mLastLocationReading != null);
// DONE - When the footerView's onClick() method is called, it must issue the
// following log call
// log("Entered footerView.OnClickListener.onClick()");
mFooterView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
log("Entered footerView.OnClickListener.onClick()");
// footerView must respond to user clicks.
// Must handle 3 cases:
// 3) There is no current location - response is up to you. The best
// solution is to disable the footerView until you have a location.
if (mLastLocationReading == null)
{
log("Location data is not available");
mFooterView.setEnabled(false);
}
// 1) The current location is new - download new Place Badge. Issue the
// following log call:
// log("Starting Place Download");
if(! mAdapter.intersects(mLastLocationReading))
{
log("Starting Place Download");
PlaceDownloaderTask pdt = new PlaceDownloaderTask(PlaceViewActivity.this);
pdt.execute(mLastLocationReading);
} else {
// 2) The current location has been seen before - issue Toast message.
// Issue the following log call:
log("You already have this location badge");
Toast.makeText(getApplicationContext(), "You already have this location badge", Toast.LENGTH_LONG).show();
}
}
});
// Attach the adapter to this ListActivity's ListView
getListView().setAdapter(mAdapter);
}
@Override
protected void onResume() {
super.onResume();
Location tempLoc;
mMockLocationProvider = new MockLocationProvider(
LocationManager.NETWORK_PROVIDER, this);
// DONE - Check NETWORK_PROVIDER for an existing location reading.
// Acquire reference to the LocationManager
if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)))
finish();
tempLoc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// Only keep this last reading if it is fresh - less than 5 minutes old.
if(tempLoc != null && age(tempLoc)