Android - GMapsV2 - Why is my activity not drawing the polyline? - java

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

Related

Get user location: Android

So I have searched the internet for lots of different solutions to get my android phone to show current location through the Google Maps API using play services. I believe I have the right set-up but something is just not right.
Please see below the .java and .xml code.
Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
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.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
}
private void centerMapOnMyLocation() {
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Location location = mMap.getMyLocation();
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
LatLng latlng;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (location != null) {
//Create a LatLng object for the current location
latlng = new LatLng(latitude, longitude);
} else {
locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="example.navigationapplication_10.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Many thanks
Try using this class to get the Latitude and Longitude..
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And for marking your position in the map
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
for(int i=0;i<MainActivity.nameArray.length;i++)
{
latitude=Double.parseDouble(MainActivity.latArray[i]);
longitude=Double.parseDouble(MainActivity.lonArray[i]);
LatLng shops = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));
}
} else {
gps.showSettingsAlert();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this Helps

how to send the data to server and update repeatedly in a certain time interval in android

this is my code of current location. i'm new to android so can anyone help me out ?
i need to send the current location to server and update it i certain time interval so that the user can fetch the location and display it on the map.it is basically a tracking device.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}

How can I get the longitude and latitude in my android app?

I've been trying to get the location for the particular phone for a while now. I have used the following code but instead of showing the location it will just crash when I try and run the app in my emulator.
Once I've got the longitude and latitude I am going to use it to map the current location on a google map!
public class Homescreen extends ActionBarActivity implements LocationListener {
final TextView t = (TextView)findViewById(R.id.textView1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
t.setText(latitude);
// Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}
Use This Activity. I hope it will help you.
package yourPackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingDefaultValue;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingKey;
import com.infologitech.spotways.custom.TransactionSupport;
public class GetCurrentLocationActivity extends Activity implements
LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
private Context context = this;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private Location mLocation;
private float minAccuracy = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (checkPlayServices()) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
//waitForLocation();
}else finish();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle arg0) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5 * 1000);
mLocationRequest.setFastestInterval(2 * 1000);
mLocationRequest.setSmallestDisplacement(5f);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
int latitude = (int) (loc.getLatitude());
int longitude = (int) (loc.getLongitude());
Toast.makeText(this,"Lat "+latitude+", Lng "+longitude);
}
}
#Override
protected void onDestroy() {
stopUpdate();
super.onDestroy();
}
private void stopUpdate() {
try {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
} catch (Exception e) {
}
}
public boolean checkPlayServices() {
final int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, context, 3434);
if (dialog != null) {
dialog.show();
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
if (ConnectionResult.SERVICE_INVALID == resultCode) {
}
}
});
return false;
}
}
return false;
}
return true;
}
}

Google Maps Android - tracking location changes

I'm developing a tracking application, for which I would also like be able to continue tracking when the application is sent to background. For this purpose I implemented a LocationListener. But clearly I'm missing something here, because during runtime none of the debug printlns appear, so the application never enters any of the inherited LocationListener functions.
michal.myapp.activities;
import java.util.ArrayList;
import java.util.Calendar;
import michal.myapp.R;
import michal.myapp.db.DataSource;
import michal.myapp.model.Track;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* #author Michał Szydłowski
*
* Class representing user's map activity with location change detection and sensors.
*
*/
public class MapActivity extends FragmentActivity implements LocationListener,
SensorEventListener{
private GoogleMap map;
private DataSource dataSource;
private SensorManager sensorManager;
private Sensor senAccelerometer;
private ArrayList <LatLng> trackPoints;
private boolean zoomEnabled;
private Button saveTrackButton;
private static final long INTERVAL = 1000;
private static final float ACCURACY = 20;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initialize();
check();
saveTrackButton = (Button) findViewById(R.id.saveTrackButton);
saveTrackButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDataFromPopupWindow();
}
});
}
private void check() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
System.out.println("yes");
}
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i("provider", "" + provider);
if (provider.equals("")) {
System.out.println("nope");
}
setUpMapIfNeeded();
}
private void initialize()
{
dataSource = new DataSource(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
trackPoints = new ArrayList <LatLng> ();
zoomEnabled = true;
}
private void getDataFromPopupWindow()
{
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.save_track_window, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
final EditText editName = (EditText) popupView.findViewById (R.id.trackName);
editName.requestFocus();
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
Button btnSave = (Button) popupView.findViewById(R.id.save);
btnSave.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String trackName = editName.getText().toString();
saveTrack(trackName);
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.update();
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
popupWindow.showAtLocation(saveTrackButton, Gravity.CENTER, 0, 0);
}
/**
* Saves the track to database when finished
*/
private void saveTrack(String trackName){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) ;
Track recordedTrack = new Track(trackName, trackPoints, date);
dataSource.open();
dataSource.insertTrack(recordedTrack);
dataSource.close();
}
/**
* Centers the view of the map around the current user's location.
* #param loc LatLng object representing user's current coordinates.
*/
private void zoom (LatLng loc)
{
if(zoomEnabled)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
zoomEnabled = false;
}
}
/** Initializes the GoogleMap object if it hasn't been already done.
* If successful, enables location tracking.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (map != null) {
//setUpMap();
setUpMap();
}
}
}
private void setUpMap()
{
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, ACCURACY, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("setupmap");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
dataSource.close();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
dataSource.open();
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] > 15 || event.values[1] > 15 || event.values[2] > 15)
{
// Intent intent = new Intent(this, CameraActivity.class);
// startActivity(intent);
}
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
trackPoints.add(loc);
map.addPolyline(new PolylineOptions().addAll(trackPoints).width(5).color(Color.BLUE));
zoom (loc);
System.out.println("location changed");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
System.out.println("status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider disabled");
}
}
I have the following permissions in my Android Manifest:
<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="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCELEROMETER"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
It is also worth mentioning, that I already try to attach an OnMyLocationChangeListener to my GoogleMap object, and it did track location changes, but not if the application was sent to background. Any ideas?

<s3dReadConfigFile:75>: Can't open file for reading error

I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.

Categories