Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

QCon

No description
by

Ricardo Ogliari

on 29 November 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of QCon

Menu
Introdução
Mapas
Simples Mapa na Tela
Objetos
Desenhando no Mapa
Interagindo com Mapa
Mudando a View
Location API
Métodos de Georeferenciamento
API
Quem eu Sou
Geolocalização no Android

Ricardo da Silva Ogliari;
Instrutor Globalcode;
Android Developer Sênior Easy Taxi;
Things Hacker Team;
StillRocker;
10 personalidades Open Hardware;
+- 250 publicações;
Campus Party, TDC, FISL, QCon..
Livro: Android - Do Básico ao Avançado
Introdução
Introdução

API faz parte do Google Services;
Precisa ser baixado no Android SDK Manager;
Introdução
Importar projeto da Google Play Service;
Novo projeto deve apontar para esta biblioteca;
Chave
* Prompt de comandos:
Colocando Mapa na Tela
Mapas

* Instalar Google Play Services Lib;
* Identificar a versão desta lib no AndroidManifest.xml;
Chave
Proprietário: CN=Android Debug, O=Android, C=US
Emissor: CN=Android Debug, O=Android, C=US
Válido de: Sun Jan 26 01:10:47 BRST 2014 a: Tue Jan 19 01:10:47 BRST 2044
Fingerprints do certificado:
MD5: E:22:F7:94:33:5D:35:1B:9E:91:F6:C9...
SHA1:
73:41:69:A2:98:5B:85:3A:E1:38:F6:C2:25:1A:83:77:62:71:93:73
SHA256: 83:7E:8C:AF:80:A6:92:13:4F:06:...
Console
* Habilitar Google Maps for Android 2.0
Console
* Uso da SHA1;

Chave
* Chave de produção ou de testes;
* SDK já provê chave de testes:
* OS X and Linux: ~/.android/
* Windows Vista and Windows 7:
C:\Users\your_user_name\.android\
* Gerar SHA1 desta chave;
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
Nova Android Key
No Manifesto da Aplicação
* Colocar a chave criada:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>
Manifesto
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>

View da Activity
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
Google Apis Console
* https://code.google.com/apis/console
* Criar Projeto;
View da Activity
Polyline
* Polyline e PolylineOptions;
* Demarcando a rua Santa Efigência;
Mapa Direcionado
Mapas Profissionais

3D
Só dar zoom e mudar ângulo;
NADA de código;
Objeto Google Map
* Ações sobre o GoogleMap;
Shapes
* Polyline
* Polygon
* Circle
<fragment ...
xmlns:map="http://schemas.android.com/apk/res-auto"
map:cameraBearing="112.5"
map:cameraTargetLat="-23.551356"
map:cameraTargetLng="-46.633043"
map:cameraTilt="30"
map:cameraZoom="13"
map:mapType="normal"
map:uiCompass="true"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="true"
map:uiZoomGestures="true" >
Tipos de Mapas
Opções para o Marker
Position: Latitude e longitude;
Anchor: ponto de âncora da imagem, padrão é no centro inferior;
Alpha: transparência;
Title;
Snippet;
Icon;
Draggable;
Visible;
Icon;
Rotation;

POI - Point Of Interest
* Uso das classes Marker e MarkerOptions
Cliques no Marker
private GoogleMap mMap;
...
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
* Ações sobre o GoogleMap;
GoogleMap map;
...
// Sets the map type to be "hybrid"
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMapType(GoogleMap.MAP_TYPE_NONE);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
LatLng latLng = new LatLng(-23.608616, -46.697124);
MarkerOptions mo = new MarkerOptions()
.position(latLng)
.title("QCon SP")
.snippet("International Software Development Conference");
mMap.addMarker(mo);
Onde será o clique?

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

@Override
public boolean onMarkerClick(Marker marker) { }
});

mMap.setOnInfoWindowClickListener(new oogleMap.OnInfoWindowClickListener() {

@Override
public void onInfoWindowClick(Marker marker) { }
});
PolylineOptions lineOpts = new PolylineOptions();
lineOpts.add(new LatLng(-23.540206,-46.63776));
lineOpts.add(new LatLng(-23.539616,-46.638297));
lineOpts.add(new LatLng(-23.538062,-46.63937));
lineOpts.add(new LatLng(-23.537294,-46.639906));
lineOpts.add(new LatLng(-23.536586,-46.640486));
lineOpts.add(new LatLng(-23.535642,-46.641129));
lineOpts.color(Color.BLUE);

Polyline polyline = mMap.addPolyline(lineOpts);
Polygon
* Polygon e PolygonOptions;
* Demarcando a igreja da Sé;

PolygonOptions polOptions = new PolygonOptions();
polOptions.add(
new LatLng(-23.551886,-46.634373),
new LatLng(-23.550784,-46.633847),
new LatLng(-23.550597,-46.634303),
new LatLng(-23.551718,-46.634829));
polOptions.strokeColor(Color.RED);
polOptions.fillColor(Color.argb(100, 0, 0, 255));

Polygon polygon = mMap.addPolygon(polOptions);
Circle
* Circle e CircleOptions;
* Chamar atenção para o QConSP;

CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(-23.608616, -46.697124))
.fillColor(Color.argb(100, 0, 0, 255))
.strokeColor(Color.GREEN)
.radius(2000);

Circle circle = mMap.addCircle(circleOptions);
Controles no Mapa
* Classe UiSettings é a chave;
* GoogleMap.getUiSettings();
* UiSettings.setZoomControlsEnabled(boolean);
* UiSettings.setCompassEnabled(boolean);
* UiSettings.setMyLocationButtonEnabled(boolean);
* UiSettings.setScrollGesturesEnabled(boolean);
* UiSettings.setTiltGesturesEnabled(boolean);
* UiSettings.setRotateGesturesEnabled(boolean);
* GoogleMap.setOnMapClickListener;
Posicionamento e Zoom
* Métodos animateCamera e moveCamera;
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
mMap.animateCamera(CameraUpdateFactory.zoomOut());
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000,null);
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(LatLng, 15)
);

Posicionamento e Zoom
* Métodos animateCamera e moveCamera;
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(-37.81319, 144.96298))
.zoom(17)
.bearing(90) //leste
.tilt(60) //ângulo para 60 graus
.build();
mMap.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition)
);
Monitoramento de Atividades
* Android monitora mudanças de estados no usuário e avisa seu aplicativo!!!
* Permissão especial: com.google.android.gms.permission.ACTIVITY_RECOGNITION;
* Client específioc para esta finalidade: ActivityRecognitionClient;
Location Service API
Location Service

* Serviço que fica requisitando a localização;
* Através de um cliente (LocationClient) somente requisitamos esta informações;
* Simples assim..
Esqueleto II
Console
* Habilitar Google Maps for Android 2.0
LocationRequest
Peguei a posição, e????
Preciso repetir? É fácil...
Esqueleto I
public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener{

protected void onCreate(Bundle savedInstanceState) {}

public void onConnectionFailed(ConnectionResult connectionResult) {}

public void onConnected(Bundle connectionHint) {}
public void onDisconnected() {}

}
Fazendo o LocationClient trabalhar
mLocationClient.requestLocationUpdates(mLocationRequest, this);

removeLocationUpdates(this);

Exemplo de PendingIntent
* Passos para ouvir atualizações;
* Criar um LocationRequest: um descritivo das propriedades da requisição de localização: tempo, custo, método, dentre outros;
* Implementar LocationListener;
* Sobrescrever onLocationChanged, método que já recebe um Location;
* Requisitar ao LocationClient através do requestLocationUpdates;

mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5000);

//HIGH_ACCURACY: GPS..
//Métodos de Posicionamento precisam de permissão
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Intent intent = new Intent(this, MyPending.class);
PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
----------------
public class MyPending extends IntentService {
protected void onHandleIntent(Intent intent) {
int transitionType = LocationClient.getGeofenceTransition(intent);
if ( transitionType == Geofence.GEOFENCE_TRANSITION_ENTER)) {
...
}
}
}
ActivityRecognitionClient rc = new ActivityRecognitionClient(this, this, this);

rc.requestActivityUpdates(
DETECTION_INTERVAL_MILLISECONDS,
mActivityRecognitionPendingIntent);

rc.disconnect();


LocationRequest
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5000);

//EXATIDÃO ALTA = GPS - AGPS

//AndroidManifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Geofence
* Criar cercas eletrônicas;
* Código permite alerta de entrada e saída em dada cerca;
* Mais de um Geofence ativos;
* Passos:
* Instância de Geofence;
* Método addGeofence na LocationClient;
* Implementar OnAddGeofencesResultListener;
* Criar PendingIntent que será o callback do listener;

private LocationClient mLocationClient;
protected void onCreate(Bundle savedInstanceState) {
mLocationClient = new LocationClient(this, this, this);
}

public void onConnectionFailed() {}

public void onConnected(Bundle connectionHint) {
Location location = mLocationClient.getLastLocation();
}
public void onDisconnected() {}

protected void onStart() {
super.onStart();
mLocationClient.connect();
}
protected void onStop() {
mLocationClient.disconnect();
super.onStop();
}

LocationListener
public class Main extends Activity implements
OnConnectionFailedListener, ConnectionCallbacks,

LocationListener
{

@Override
public void onLocationChanged(Location loc) {
mMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 15));
}
}
Geofence
public class MainActivity extends Activity implements
OnAddGeofencesResultListener {

public void onAddGeofencesResult(int stCode, String[] ids) {}

...
Geofence g = new Geofence.Builder()
.setRequestId(getId())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(getLatitude(), getLongitude(), getRadius())
.setExpirationDuration(mExpirationDuration)
.build();
mLocationClient.addGeofences(List<Geofence>, PendingIntent, this)
...
Exemplo de PendingIntent
public class ActivityRecognitionIntentService extends IntentService {
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult r = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbableActivity = r.getMostProbableActivity();

int activityType = mostProbableActivity.getType();
switch(activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
...
}
}
}
Cell ID
Bônus Track - CellID

Estações Rádio Base estão em um ponto geográfico;
Basta saber qual célula o smartphone está;
Código, Código, Código
final TelephonyManager t = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

if (t.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) telephony.getCellLocation();
if (location != null) {
location.getLac();
location.getCid();
t.getNetworkOperator();//MCCMNC
}
}
E agora?
* Open CellID;
* www.opencellid.org/cell/get?key=apikey&mnc=1&mcc=2&lac=200&cellid=234
Obrigado QCon;
Obrigado André;
Obrigado platéia;

Dúvidas?????

rogliariping@gmail.com
@mobilidadetudo
Full transcript