这是我与位置更新MapsActivity类,你可以使用我的代码
package com.example.vishal.gpsloc;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, com.google.android.gms.location.LocationListener, GoogleMap.OnMapClickListener, ResultCallback<Status> {
GoogleMap mMap;
private MarkerOptions marker1, marker2;
private final int GEOFENCE_REQ_CODE = 0;
private GoogleApiClient googleApiClient;
private double longitude;
private double latitude;
double lat,lon;
List latt=new ArrayList();
List longi=new ArrayList();
Location lastLocation;
String ip=null;
SharedPreferences pref;
SharedPreferences.Editor editor;
int flag=1;String cityName,stateName,countryName,root;
private ArrayList<LatLng> points; //added
Polyline line; //added
File log,myDir;
private static MQTT mqtt;
private static BlockingConnection connection;
private final int UPDATE_INTERVAL = 60000 ;
private final int FASTEST_INTERVAL = 60000 ;
private static final float SMALLEST_DISPLACEMENT = 0.25F; //quarter of a meter
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()), cord, devname, devid = android.os.Build.SERIAL;
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
CheckConnection();
if (!isGooglePlayServicesAvailable()) {
System.out.println(" My Google Play Not Available");
finish();
}
points = new ArrayList<LatLng>(); //added
setContentView(R.layout.route_mapper);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
InitializeDB();
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PunchStop();
}
});
if (this.mMap != null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
mMap.setMyLocationEnabled(true);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
mqtt=new MQTT();
try{
if(ip==null){
System.out.println("Mqtt Initialized in Maps Activity");
ip="demo.aiotm.in:1883";
}
//mqtt.setHost("tcp://"+ip);
mqtt.setHost("tcp://10.30.60.242:1883");
connection = mqtt.blockingConnection();
connection.connect();
}catch (Exception e){
e.printStackTrace();
}
}
private void InitializeDB() {
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
editor = pref.edit();
if (isExternalStorageReadable() == true && isExternalStorageWritable() == true) {
root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/GpsTracking");
myDir.mkdirs();
log = new File (myDir, "GpsLog");
if (myDir.exists()) {
System.out.println("Directory Already Exsists............");
} else {
try {
myDir = new File(root + "/GpsTracking");
myDir.mkdirs();
log = new File (myDir, "GpsLog");
} catch (Exception e) {
Toast.makeText(getBaseContext()
,e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}else {Toast.makeText(getBaseContext(),
"Permissions Not Availiable'",
Toast.LENGTH_SHORT).show();}
}
private void PunchStop() {
System.out.println("stop Location is "+latitude+","+longitude+"\t"+cityName );
try {
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
PrintWriter out = new PrintWriter(new FileWriter(log, true));
out.append(currentDateTimeString+"\t"+latitude+","+longitude+"\t"+cityName+"\n");
out.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'GpsLog.txt'",
Toast.LENGTH_SHORT).show();
}catch (Exception e){e.printStackTrace();}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void CheckConnection() {
String answer=null;
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
answer="You are connected to a WiFi Network";
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
answer="You are connected to a Mobile Network";
}
else
answer = "No internet Connectivity";
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
getCurrentLocation();
mMap.setOnMapLongClickListener(this);
mMap.setOnMapClickListener(this);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_POWER) {
//Handle what you want in long press.
Toast.makeText(getApplicationContext(),"Power Key Pressed",Toast.LENGTH_LONG).show();
flag=1;
return true;
}
return super.onKeyLongPress(keyCode, event);
}
private void getCurrentLocation() {
//mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
System.out.println("Parameters are ::" + latitude + ":" + longitude);
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation(latitude, longitude, 1);
cityName = addresses.get(0).getAddressLine(0);
stateName = addresses.get(0).getAddressLine(1);
countryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
.draggable(true)
.title(cityName))
.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i("info", "Connection Failed");
try {
// connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Toast.makeText(MapsActivity.this, "Connected", Toast.LENGTH_SHORT).show();
getCurrentLocation();
Log.i("info", "onConnected()");
getLastKnownLocation();
}
private void getLastKnownLocation() {
Log.d("INFO", "getLastKnownLocation()");
System.out.println("info :: getLastKnownLocation");
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
Log.i("INFO", "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w("INFO", "No location retrieved yet");
startLocationUpdates();
}
}
private LocationRequest locationRequest;
// Start location Updatess
private void startLocationUpdates() {
Log.i("INFO", "startLocationUpdates()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
editor = pref.edit();
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setSmallestDisplacement(SMALLEST_DISPLACEMENT)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
}
@Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
marker1 = null;
marker2 = null;
getCurrentLocation();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override
public void onMapClick(LatLng latLng) {
}
@Override
public void onLocationChanged(Location location) {
Log.d("INFO", "onLocationChanged ["+location+"]");
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getAddressLine(0);
stateName = addresses.get(0).getAddressLine(1);
countryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
e.printStackTrace();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title(cityName))
.showInfoWindow();
points.add(latLng);
redrawline();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
lastLocation = location;
writeActualLocation(location);
}
private void redrawline() {
mMap.clear(); //clears all Markers and Polylines
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int i = 0; i < points.size(); i++) {
LatLng point = points.get(i);
options.add(point);
}
getCurrentLocation(); //add Marker in current position
line = mMap.addPolyline(options); //add Polyline
}
// Write location coordinates on UI
private void writeActualLocation(Location location) {
Log.d("Actual Lat: ", String.valueOf(location.getLatitude()));
Log.d("Actual Long: ", String.valueOf(location.getLongitude()));
lat=location.getLatitude();
lon=location.getLongitude();
LatLng latLng=new LatLng(lat,lon);
mMap.addMarker(new MarkerOptions()
.position(latLng));
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
@Override
public void onResult(@NonNull Status status) {
Log.i("INFO", "onResult: " + status);
if (status.isSuccess()) {
System.out.println("Status Succes");
Toast.makeText(getApplicationContext(),"Status Succes",Toast.LENGTH_LONG).show();
// drawGeofence();
} else {
System.out.println("Status failed");
Toast.makeText(getApplicationContext(),"Status Failed",Toast.LENGTH_LONG).show();
}
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
}
结帐请:https://stackoverflow.com/a/38397092/5955362 –
是LocationServices.FusedLocationApi正在检查NETWORK_PROVIDER和GPS_PROVIDER? –
谢谢@JaydeepPatel融合是惊人的.. !!! –