I am using the classic GPS tracker code to retrieve my current location, but I always get 0 as a return for both lat and lon, even though I try to change positions its still always 0. please note that I have used the following code in previews apps and it worked.
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.apostolis.map1sttest">
<!-- Permition list bellow !-->
<uses-permission android:name="android.permission.INTERNET" /> <!-- internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- internet 3g/4g enabled-->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- Google accounts -->
<uses-permission android:name="android.permission.NETWORK" /> <!-- internet -->
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- Google acconts -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- phone info -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- GPS -->
<uses-feature android:name="android.hardware.location.gps" /> <!-- GPS (needed for android 5.0+) -->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
GPStracker.java
package com.example.apostolis.map1sttest;
import android.app.AlertDialog;
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;
import android.support.annotation.Nullable;
import android.widget.Toast;
/**
* Created by Apostolis on 10/27/2016.
*/
public class GPStracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longituzzde;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 100;
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 && !isGPSEnabled) {
} 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.NETWORK_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(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enabled.Go to Settings menu and enable it?");
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) {
this.location = location;
getLatitude();
getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.example.apostolis.map1sttest;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GPStracker gps;
private String lat,lon;
Button btnGetLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double mCurrentLatitude,mCurrentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetLocation = (Button) findViewById(R.id.btgps);
//creating onClick listener for GPS.
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPStracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
lat = Double.toString(latitude);
lon = Double.toString(longitude);
Toast.makeText(MainActivity.this,
"Your Location is: Lat: " + lat.toString() + " Lon:" + lon.toString(), Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
};
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.apostolis.map1sttest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/btgps" />
</RelativeLayout>
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
Toast.makeText(this, location.getLatitude() + " * ********"+location.getLongitude(), Toast.LENGTH_LONG).show();
}
}
create variables
private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
add this inside your onCreate method
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
and add this inside your onResume
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
Log.e("Google API", "Connecting");
mGoogleApiClient.connect();
}
Related
I get empty NMEA messages and onLocationChanged(Location) is never called when requesting gps coordinates. It only works when requesting via the network provider but then I get an accuracy of 2000 meters, same with fused provider.
This is my activity:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
public class MainActivity extends Activity implements LocationListener, OnNmeaMessageListener, ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = "MainActivity";
Context context;
double latitude;
double longitude;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
check_permission();
start_gps_manager();
}
#Override
public void onRequestPermissionsResult(int i, #NonNull String[] strings, #NonNull int[] ints) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void check_permission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(this, PERMISSIONS, 112);
}
}
LocationManager gpsLocationManager;
private void start_gps_manager() {
gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.e(TAG, "Requesting GPS location updates");
// gps satellite based
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
gpsLocationManager.addNmeaListener(this);
}
public void onPause() {
super.onPause();
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.e(TAG, latitude + " - " + longitude);
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onNmeaMessage(String s, long l) {
Log.e(String.valueOf(l), s);
}
}
And part of the AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The NMEA messages don't contain gps nor time data. How can I resolve this issue and get accurate gps coordinates.
In case anyone comes across the same issue in the future: GPS needs to acquire a fix before the application can receive valid gps coordinates. This takes some time depending on how good of a connection the gps module has to the gps satellites. This means that you'll have to wait until you are able to acquire gps coordinates.
I have created an app which determines the speed of car using GPS/Network Provider.
Here is what I tried, the code is fine there is no errors but app crashes when I run it.
AndroidGPSTrackingActivity:
package com.example.muhammadshahid.smartsm;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends AppCompatActivity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_gpstracking);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
GPSTracker:
package com.example.muhammadshahid.smartsm;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
/**
* Created by Muhammad Shahid on 2/23/2017.
*/
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
// check self permission
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission
(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission
(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS() {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission
( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission
( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
//requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ASK_PERMISSIONS);
}
locationManager.removeUpdates(GPSTracker.this);
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Activity_tracker_xml File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_android_gpstracking"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.muhammadshahid.smartsm.AndroidGPSTrackingActivity">
<Button
android:text="ShowLocation"
android:id="#+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="203dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Minifest.xml File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.muhammadshahid.smartsm">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".AndroidGPSTrackingActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
setContentView(R.layout.activity_android_gpstracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
//add this line you missing the button declaration
I'm new to android developing, and i'm tring to create an app which gets your coordinates like this tutorial http://developer.android.com/training/location/receive-location-updates.html
but my app crashes. I didn't to the last part "Save the State of the Activity" because i dont know what my LOCATION_KEY or REQUESTING_LOCATION_UPDATES_KEY is.
my code:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
GoogleApiClient mGoogleApiClient;
TextView mLatitudeText;
TextView mLongitudeText;
TextView mcLatitudeText;
TextView mcLongitudeText;
Location mLastLocation;
Location mCurrentLocation;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
mLatitudeText = (TextView) findViewById(R.id.lat);
mLongitudeText = (TextView) findViewById(R.id.lon);
mcLatitudeText = (TextView) findViewById(R.id.llat);
mcLongitudeText = (TextView) findViewById(R.id.llon);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
createLocationRequest();
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
dialogBuilder.setMessage("onStop");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mCurrentLocation = mLastLocation;
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
//modified
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
dialogBuilder.setMessage("onLocationChanged");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
updateUI();
}
public void updateUI()
{
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
mcLatitudeText.setText(String.valueOf(mCurrentLocation.getLatitude()));
mcLongitudeText.setText(String.valueOf(mCurrentLocation.getLongitude()));
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
}
And this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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="#android:style/Theme.Holo"
<activity
android:name=".LoginScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/title_activity_register" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<activity
android:name=".StepCounter"
android:label="#string/title_activity_step_counter" >
</activity>
</application>
When i run my app with the emulator (which doesn't have google services) and i click the update google services i get this error (i don't think this is the problem because i have google services on my phone) :
08-26 09:54:24.640 7191-7191/com.persasrl.paul.quickfit E/SettingsRedirect﹕ Can't redirect to app settings for Google Play services
08-26 09:54:24.653 7191-7191/com.persasrl.paul.quickfit D/AndroidRuntime﹕ Shutting down VM
08-26 09:54:24.654 7191-7191/com.persasrl.paul.quickfit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.persasrl.paul.quickfit, PID: 7191
java.lang.RuntimeException: Unable to pause activity {com.persasrl.paul.quickfit/com.persasrl.paul.quickfit.StepCounter}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3613)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.zzf.zzb(Unknown Source)
at com.google.android.gms.common.api.zzg.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.removeLocationUpdates(Unknown Source)
at com.persasrl.paul.quickfit.StepCounter.stopLocationUpdates(StepCounter.java:148)
at com.persasrl.paul.quickfit.StepCounter.onPause(StepCounter.java:144)
at android.app.Activity.performPause(Activity.java:6101)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1310)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3603)
I tried to delete the startLocationUpdates part and it doesn't crash anymore... but also it doesn't update location...
SOLVED IT
so the problem was that i declared mLocationRequest twice at the start of the project:
LocationRequest mLocationRequest;
and in
createLocationRequest()
LocationRequest mLocationRequest = new LocationRequest();
i changed in crateLocationRequest LocationRequest mLocationRequest = new LocationRequest(); to mLocationRequest = new LocationRequest(); and now it doesn't crash.
Problem is when I run service on emulator(android 4.0.3), then all is working(data is sent once per hour), but when i run it on my phone it's start sending data every minute. I can't figure out why, hope someone can help me with this.
The service is sending data to http://gprsbtn.herokuapp.com/coordinates where it's going to database.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aravov.gprsbtn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.aravov.gprsbtn.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MyService"></service>
<receiver android:name=".AlarmReciever"/>
</application>
</manifest>
MainActivity.java
package com.aravov.gprsbtn;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
final String LOG_TAG = "myLogs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClc(View v) {
startService(new Intent(this, MyService.class));
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
}
public void btnClc2(View v) {
stopService(new Intent(this, MyService.class));
}
}
GPSTracker.java
package com.aravov.gprsbtn;
import android.app.AlertDialog;
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;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
package com.aravov.gprsbtn;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
PendingIntent pendingIntent;
AlarmManager alarmManager;
BroadcastReceiver mReceiver;
final String LOG_TAG = "myLogs";
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "onCreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
someTask();
sendNotif();
return super.onStartCommand(intent, flags, startId);
}
public void sendNotif() {
Notification notification = new Notification(R.drawable.ic_stat_gprsbtn, "Text in status bar",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "Notification's title", "Notification's text", pendingIntent);
startForeground(1992, notification);
}
public void onDestroy() {
stop();
super.onDestroy();
Log.d(LOG_TAG, "onDestroy");
}
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
void someTask() {
mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
action();
}
};
registerReceiver(mReceiver, new IntentFilter("gprs.post"));
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("gprs.post"),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// timer here <<< 1000 * 60 = 1 minute
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, 1000 * 60 * 60 , pendingIntent);
}
public void action() {
GPSTracker gps = new GPSTracker(MyService.this);
//final double latitude = gps.getLatitude();
//final double longitude = gps.getLongitude();
final String lat = Double.toString(gps.latitude);
final String lon = Double.toString(gps.longitude);
// check if GPS enabled
if(gps.canGetLocation())
{
//posting
Thread t = new Thread(){
public void run(){
postData(lat, lon);
}
};
t.start();
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
public void postData(String latitude, String longitude) {
try {
HttpParams p = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(p);
HttpPost post = new HttpPost("http://gprsbtn.herokuapp.com/coordinates");
JSONObject params = new JSONObject();
params.put("latitude",latitude);
params.put("longitude",longitude);
StringEntity ent = new StringEntity(params.toString());
post.setEntity(ent);
post.setHeader("Content-type", "application/json");
client.execute(post);
Log.d(LOG_TAG, "onDataSent");
} catch (Exception e) {
e.printStackTrace();
}
}
// stop the alarm receiver
public void stop() {
try {
unregisterReceiver(mReceiver);
Toast.makeText(this, "Service stoped", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
}
I work an application which return a position of the user and it gets information from GPS.
and send position to email Following code is there, it is working perfectly on Android 2.3 but on Android 4.2.2 it doesn't work. on Android 4.2.2 device and emulator doesn't work. This
code for GPS Tracker:
package com.example.safetymobile;
//package com.example.gpstracking;
import android.app.AlertDialog;
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;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager .NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
GPS :
package com.example.safetymobile;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class GPS extends Activity {
String NotifyWay="";
CheckBox chk,chk1;
EditText edt,edt1;
Button btn;
GPSTracker gps;
public int time = 0;
public Timer t = new Timer();
int interval = 1;
int counter = 0;
int counterend = 2;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
Date stopt = cal.getTime();
int StopTime = 0;
#SuppressLint("SimpleDateFormat")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
#SuppressWarnings("unused")
DateFormat date = new SimpleDateFormat("HH:mm a");
//chk=(CheckBox)findViewById(R.id.notiEmail);
//chk1=(CheckBox)findViewById(R.id.notisms);
edt=(EditText)findViewById(R.id.interval);
edt1=(EditText)findViewById(R.id.timeStop);
//email
/*chk.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(NotifyWay.equals(""))
{
NotifyWay="Email";
}
else
{
NotifyWay="Email";
chk1.setChecked(false);
//Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
}
}
});*/
/*chk1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(NotifyWay.equals(""))
{
NotifyWay="SMS";
}
else
{
NotifyWay="SMS";
chk.setChecked(false);
//Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
}
}
});*/
btn=(Button)findViewById(R.id.DoneAdd);
btn.setOnClickListener(new OnClickListener(){
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
int val=Integer.parseInt(edt.getText().toString());
StopTime=Integer.parseInt(edt1.getText().toString());
interval=val*60000;
SQLiteDatabase db;
db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_setting =
"CREATE TABLE GPS ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "valTime INTEGER,"
+ "stopTime INTEGER);";
db.execSQL(CREATE_TABLE_setting);
ContentValues values1 = new ContentValues();
values1.put("valTime", interval);
values1.put("stopTime", StopTime);
db.insert("Setting", null, values1);
//Convert Minute To Milliseconds
stopt.setHours(currentLocalTime.getHours() + StopTime);
tt();
Intent intent = new Intent(GPS.this, Change_setting.class);
startActivity(intent);
}
});
}
#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_gps, menu);
return true;
}
public void tt()
{
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#SuppressWarnings("deprecation")
#Override
public void run() {
currentLocalTime = cal.getTime();
//// .....
if(currentLocalTime.compareTo(stopt) > 0)
{
t.cancel();
}
else
Toast.makeText(getApplication(), "d < d1", Toast.LENGTH_LONG).show();
gps = new GPSTracker(GPS.this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String text ="https://Maps.google.com/maps?q=" + Double.toString(latitude) + "," + Double.toString(longitude) ;// latitude
//............................
String em="";
//String pn="";
//SharedPreferences pref = getSharedPreferences("pref",0);
//SharedPreferences.Editor edit = pref.edit();
//String pn= pref.getString("PhNum", null);
//edit.commit();
SQLiteDatabase db;
db = openOrCreateDatabase(
"Saftey.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
Cursor cur = db.query("info", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false)
{
//pn = cur.getString(0);
em=cur.getString(3);
cur.moveToNext();
}
cur.close();
// if(NotifyWay.equals("Email"))
// {
SendingEmail(em, text);
// }
/* else
{
if(NotifyWay.equals("SMS"))
{
SendingSMS(pn, text);
}
}*/
//......................
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
//// .....
time += 1;
}
});
}
}, 0, interval);
}
public void SendingEmail(String em, String text)
{
Mail m = new Mail("mbrm.yu#gmail.com", "mbrm_yu123");
String[] toArr = {em};
m.setTo(toArr);
m.setFrom("mbrm.yu#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
//m.setBody("I'm in Danger Dad, please Help ...");
m.setBody(text);
try
{
//m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(getApplication(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplication(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplication(), "There was a problem sending the email to : " + em, Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
/*public void SendingSMS(String pn, String text)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(pn, null, text, sentPI, deliveredPI);
}*/
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.safetymobile"
android:versionCode="2"
android:versionName="1.2" >
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" >
</uses-permission>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.safetymobile.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen"
android:clearTaskOnLaunch="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.safetymobile.ContactList"
android:label="#string/title_activity_contact_list" >
</activity>
<activity
android:name="com.example.safetymobile.Change_setting"
android:label="#string/title_activity_change_setting"
android:clearTaskOnLaunch="true" >
</activity>
<activity
android:name="com.example.safetymobile.CallContent"
android:label="#string/title_activity_call_content"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.example.safetymobile.SMS"
android:label="#string/title_activity_sms"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.example.safetymobile.Alication_list"
android:label="#string/title_activity_alication_list" >
</activity>
<activity
android:name="com.example.safetymobile.Apps"
android:label="#string/title_activity_apps"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen">
</activity>
<activity
android:name="com.example.safetymobile.Pass"
android:label="#string/title_activity_pass" >
</activity>
<activity
android:name="com.example.safetymobile.ChangePass"
android:label="#string/title_activity_change_pass" >
</activity>
<activity
android:name="com.example.safetymobile.GPS"
android:label="#string/title_activity_gps" >
</activity>
<activity
android:name="com.example.safetymobile.LightActivity"
android:label="#string/title_activity_light"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<receiver android:name=".StartupActivity">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
</manifest>
please any help?
getting address in android using web service
See the answer i have posted. my code works fine, but in android version 4.0 and above, you have to manually open GPS. You can not open it programmatically
Save yourself some trouble and just use Google Play Services Locations API. They provide a good implementation and precise location if you have Play Services installed on your device (most of devices do now)