Commit 03066bd7 authored by Vytor Calixto's avatar Vytor Calixto 👾
Browse files

Merge branch 'view' into 'develop'

View



See merge request !4
parents d32eea39 6007cd68
.gradle
.idea/
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
*/**/*.properties
*/**/*.idea
*.idea
*/**/*.iml
*.iml
app/gradle/
app/gradlew/
gradlew*
gradle/
......@@ -2,11 +2,16 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ufpr.inf.pet.geoloc" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
......@@ -17,8 +22,5 @@
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>
This diff is collapsed.
package ufpr.inf.pet.geoloc;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
/**
* Created by pet on 23/09/15.
*/
public class GeolocLocationListener implements LocationListener {
private boolean upateMapView = true;
private boolean stopped;
private MapView mapView;
private String provider;
private boolean providerEnabled = false;
public GeolocLocationListener(MapView mapView) {
this.mapView = mapView;
}
public void stop() {
stopped = true;
mapView = null;
}
@Override
public void onLocationChanged(Location location) {
if(!stopped && location != null) {
this.mapView.setGpsLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy());
this.mapView.postInvalidate();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
package ufpr.inf.pet.geoloc;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity implements LocationListener {
protected static final String TAG = "geoloc";
/**
* Última localização obtida
*/
private Location lastLocation;
private LocationManager locationManager;
private TextView latitudeText;
private TextView longitudeText;
private TextView altitudeText;
private String provider;
private boolean pausado;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//não está pausado (em segundo plano)
pausado = false;
public class MainActivity extends Activity {
//Pegamos a referência as TextViews que vamos modificar
latitudeText = (TextView) findViewById(R.id.latitude_label);
longitudeText = (TextView) findViewById(R.id.longitude_label);
altitudeText = (TextView) findViewById(R.id.altitude_label);
public static String TAG = "GEOLOC:";
//Construímos o locationManager e pegamos o serviço em execução
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Constant strings used in onSaveInstanceState, onRestoreInstanceState
private final class Save
{
public final static String GPS_LON = "gpsLon";
public final static String GPS_LAT = "gpsLAT";
public final static String GPS_ALT = "gpsALT";
public final static String GPS_ACC = "gpsAcc";
}
// Constant strings to save settings in SharedPreferences
// Also used for restoring settings
private final class Pref
{
public final static String SEEK_LON = "seek_lon";
public final static String SEEK_LAT = "seek_lat";
public final static String ZOOM = "zoom";
}
private MapView mapView;
private GeolocLocationListener locationListener;
private TilesProvider tilesProvider;
private Location savedGpsLocation;
//Se o GPS não estiver habilitado alertamos o usuário com uma dialog para que ele habilite
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled){
DialogFragment dialog = new EnableGpsDialogFragment();
dialog.show(getFragmentManager(), "habilitar gps");
}
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
lastLocation = locationManager.getLastKnownLocation(provider);
private void initViews(){
tilesProvider = new TilesProvider(getApplicationContext());
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mapView = new MapView(this, displayMetrics.widthPixels, displayMetrics.heightPixels, tilesProvider);
if(lastLocation != null){
Log.d(TAG, "Provedor " + provider + " foi selecionado.");
}else{
latitudeText.setText(R.string.no_location_detected);
longitudeText.setText(R.string.no_location_detected);
altitudeText.setText(R.string.no_location_detected);
if(savedGpsLocation != null) {
mapView.setGpsLocation(savedGpsLocation);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
mapView.refresh();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// Zooming
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_Z)
{
mapView.zoomIn();
return true;
}
// Zooming
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_X)
{
mapView.zoomOut();
return true;
}
// Enable auto follow
if (keyCode == KeyEvent.KEYCODE_H || keyCode == KeyEvent.KEYCODE_FOCUS)
{
mapView.followMarker();
return true;
}
// Simula estar no PET Computação, para testes
else if (keyCode == KeyEvent.KEYCODE_M || keyCode == KeyEvent.KEYCODE_MENU)
{
mapView.setGpsLocation(-25.45072, -49.232287, 1000, 182);
mapView.invalidate();
return false;
}
return super.onOptionsItemSelected(item);
return super.onKeyDown(keyCode, event);
}
/* Request updates at startup */
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
// Called manually to restore settings from SharedPreferences
void restoreMapViewSettings()
{
SharedPreferences pref = getSharedPreferences("View_Settings", MODE_PRIVATE);
//não está pausado (em segundo plano)
pausado = false;
double lon, lat;
int zoom;
lon = Double.parseDouble(pref.getString(Pref.SEEK_LON, "0"));
lat = Double.parseDouble(pref.getString(Pref.SEEK_LAT, "0"));
zoom = pref.getInt(Pref.ZOOM, 0);
mapView.setSeekLocation(lon, lat);
mapView.setZoom(zoom);
mapView.refresh();
}
/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
// Called manually to save settings in SharedPreferences
void saveMapViewSettings()
{
SharedPreferences.Editor editor = getSharedPreferences("View_Settings", MODE_PRIVATE).edit();
//foi pausado (está em segundo plano)
pausado = true;
PointD seekLocation = mapView.getSeekLocation();
editor.putString(Pref.SEEK_LON, Double.toString(seekLocation.getX()));
editor.putString(Pref.SEEK_LAT, Double.toString(seekLocation.getY()));
editor.putInt(Pref.ZOOM, mapView.getZoom());
editor.commit();
}
@Override
public void onLocationChanged(Location location) {
float lat;
float lng;
float alt;
do {
lat = (float) (location.getLatitude());
lng = (float) (location.getLongitude());
alt = (float) (location.getAltitude());
}while(!pausado && location == null); //Só atualiza os textos se não estiver pausado e o location tiver uma posição
latitudeText.setText("Latitude: " + String.valueOf(lat));
longitudeText.setText("Longitude: " + String.valueOf(lng));
altitudeText.setText("Altitude: " + String.valueOf(alt));
protected void onPause() {
// Save settings before leaving
saveMapViewSettings();
// Mainly releases the MapView pointer inside the listener
locationListener.stop();
// Unregistering our listener
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
// Closes the source of the tiles (Database in our case)
tilesProvider.close();
// Clears the tiles held in the tilesProvider
tilesProvider.clear();
// Release mapView pointer
mapView = null;
super.onPause();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
protected void onSaveInstanceState(Bundle outState)
{
if (mapView.getGpsLocation() != null)
{
outState.putDouble(Save.GPS_LON, mapView.getGpsLocation().getLongitude());
outState.putDouble(Save.GPS_LAT, mapView.getGpsLocation().getLatitude());
outState.putDouble(Save.GPS_ALT, mapView.getGpsLocation().getAltitude());
outState.putFloat(Save.GPS_ACC, mapView.getGpsLocation().getAccuracy());
}
super.onSaveInstanceState(outState);
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Novo provedor habilitado: " + provider);
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
double gpsLon, gpsLat, gpsAlt;
float gpsAcc;
gpsLon = savedInstanceState.getDouble(Save.GPS_LON, 999);
gpsLat = savedInstanceState.getDouble(Save.GPS_LAT, 999);
gpsAlt = savedInstanceState.getDouble(Save.GPS_ALT, 999);
gpsAcc = savedInstanceState.getFloat(Save.GPS_ACC, 999);
if (gpsLon != 999 && gpsLat != 999 && gpsAlt != 999 && gpsAcc != 999)
{
savedGpsLocation = new Location(LocationManager.GPS_PROVIDER);
savedGpsLocation.setLongitude(gpsLon);
savedGpsLocation.setLatitude(gpsLat);
savedGpsLocation.setAltitude(gpsAlt);
savedGpsLocation.setAccuracy(gpsAcc);
}
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Provedor desabilitado: " + provider);
protected void onResume() {
initViews();
restoreMapViewSettings();
locationListener = new GeolocLocationListener(mapView);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled){
DialogFragment dialog = new EnableGpsDialogFragment();
dialog.show(getFragmentManager(), "habilitar gps");
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
setContentView(mapView);
super.onResume();
}
}
package ufpr.inf.pet.geoloc;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.location.Location;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.util.Collection;
/**
* Created by pet on 23/09/15.
*/
public class MapView extends View {
private Context context;
private int viewWidth;
private int viewHeight;
private TilesProvider tilesProvider;
private TilesManager tilesManager;
private Paint fontPaint;
private Paint circlePaint = new Paint();
private Paint bitmapPaint = new Paint();
private PointD seekLocation = new PointD(0,0);
private Location gpsLocation = null;
private boolean autoFollow;
private PointD lastTouchPos = new PointD(-1, -1);
public MapView(Context context, int viewWidth, int viewHeight, TilesProvider tilesProvider) {
super(context);
this.context = context;
this.tilesProvider = tilesProvider;
this.viewHeight = viewHeight;
this.viewWidth = viewWidth;
Log.d(MainActivity.TAG, "width: " + viewWidth + " height: " + viewHeight);
tilesManager = new TilesManager(256, viewWidth, viewHeight);
initPaints();
fetchTiles();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// Define a largura e altura que foram passadas no contrutor como a dimensão da view
setMeasuredDimension(viewWidth, viewHeight);
}
private void initPaints() {
fontPaint = new Paint();
fontPaint.setColor(Color.DKGRAY);
fontPaint.setShadowLayer(1, 1, 1, Color.BLACK);
fontPaint.setTextSize(20);
circlePaint.setARGB(80, 112, 33, 255);
circlePaint.setAntiAlias(true);
}
private void fetchTiles() {
tilesManager.setLocation(seekLocation);
Rect regiaoVisivel = tilesManager.getAreaVisivel();
Rect rect = new Rect(0, 0, 2, 2);
tilesProvider.fetchTiles(rect, tilesManager.getZoom());
Log.d(MainActivity.TAG, "zoom: " + tilesManager.getZoom());
Log.d(MainActivity.TAG, "regiaoVisivel: " + regiaoVisivel.toString());
Log.d(MainActivity.TAG, "Quantas tiles? " + tilesProvider.getTiles().values().size());
}
public void drawTiles(Canvas canvas, Point offset){
Collection<Tile> tilesList = tilesProvider.getTiles().values();
Log.d(MainActivity.TAG, "tilesList.size(): " + tilesList.size());
Log.d(MainActivity.TAG, "regiaoVisivel: " + tilesManager.getAreaVisivel().toString());
for(Tile tile : tilesList) {
int tileSize = tilesManager.getTamTile();
long tileX = tile.getX() * tileSize;
long tileY = tile.getY() * tileSize;
Log.d(MainActivity.TAG, "offset: " + offset + " tileX, tileY: " + tileX + " ," + tileY);
long finalX = tileX ;//- offset.x;
long finalY = tileY ;//- offset.y;
Log.d(MainActivity.TAG, "finalX, finalY: " + finalX + ", " + finalY);
canvas.drawBitmap(tile.getImg(), finalY, finalX, bitmapPaint);
}
}
public void drawMarker(Canvas canvas, Point offset) {
if(gpsLocation != null) {
Point markerPos = tilesManager.longLatToXY(gpsLocation.getLongitude(), gpsLocation.getLatitude());
int markerX = markerPos.x ;//- offset.x;
int markerY = markerPos.y ;//- offset.y;
Log.d(MainActivity.TAG, "Marker(x,y): (" + markerX + ", " + markerY + ")");
float ground = (float) tilesManager.calcGroundResolution(gpsLocation.getLatitude());
float rad = gpsLocation.getAccuracy() / ground;
Log.d(MainActivity.TAG, "raio: " + rad);
canvas.drawCircle(markerX, markerY, 5, circlePaint);
int pen = 1;
canvas.drawText("lon:" + gpsLocation.getLongitude(), 0, 20 * pen++, fontPaint);
canvas.drawText("lat:" + gpsLocation.getLatitude(), 0, 20 * pen++, fontPaint);
canvas.drawText("alt:" + gpsLocation.getAltitude(), 0, 20 * pen++, fontPaint);
canvas.drawText("Zoom:" + tilesManager.getZoom(), 0, 20 * pen++, fontPaint);
}
}
@Override
public void onDraw(Canvas canvas){
canvas.drawARGB(255, 100, 100, 100);
PointD centerRatio = TilesManager.calcRatio(seekLocation.getX(), seekLocation.getY());
int mapWidth = tilesManager.tamanhoMapa() * 256;
Point centerPixel = new Point((int) (centerRatio.getX() * mapWidth), (int) (centerRatio.getY() * mapWidth));
Point offset = new Point((int) (centerPixel.x - viewWidth / 2f), (int) (centerPixel.y - viewHeight / 2f));
drawTiles(canvas, offset);
drawMarker(canvas, offset);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN)
{
// Keep touch position for later use (dragging)
lastTouchPos.setX((int) event.getX());
lastTouchPos.setY((int) event.getY());
return true;
}
else if (action == MotionEvent.ACTION_MOVE)
{
autoFollow = false;
PointD current = new PointD(event.getX(), event.getY());
// Find how many pixels the users finger moved in both x and y
PointD diff = new PointD(current.getX() - lastTouchPos.getX(), current.getY() - lastTouchPos.getY());
// In a full wolrd map, get the position of the center of the view in pixels
Point pixels1 = tilesManager.longLatToXY(seekLocation.getX(), seekLocation.getY());
// Subtract diff from that position
Point pixels2 = new Point(pixels1.x - (int) diff.getX(), pixels1.y - (int) diff.getY());