GPS coordinates are not updating - android

I am building app that tracks distance traveled. At the moment, I am having trouble displaying the coordinates. The code runs, but the Distance, which I've set to display the coordinates when Start is clicked, displays 0.00 when clicked.
public class MainActivity extends Activity {
private Button historyButton, startButton, stopButton;
private TextView Distance;
double currentDistance;
private SensorManager sensorManager;
private Chronometer TimeRan;
private LocationManager mLocManager;
private LocationListener location;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all buttons and textviews
historyButton = (Button) findViewById(R.id.History);
startButton = (Button) findViewById(R.id.Start);
stopButton = (Button) findViewById(R.id.Stop);
Distance = (TextView) findViewById(R.id.Distance);
TimeRan = (Chronometer) findViewById(R.id.Time_Spent);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
location = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentDistance += .01;
Distance.append("/n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 100:
configureButton();
break;
default:
break;
}
}
public void configureButton(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,100);
}
return;
}
//Request update every minute or 16 meters
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ignore permission
mLocManager.requestLocationUpdates("gps", 60000, 16, location);
}
});
};
public void GoToHistory(View v) {
Intent history = new Intent(this, History.class);
startActivity(history);
}
protected void EndWorkout(View v){
TimeRan.stop();
//ignore permission
mLocManager.removeUpdates(location);
}
}
Here is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stuyk.runningapplication">
<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"/>
<uses-feature android:name="android.hardware.sensor.stepcounter"/>
<uses-feature android:name="android.hardware.sensor.stepdetector"/>
<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>
<activity android:name=".History" />
</application>
</manifest>

locationManager.requestLocationUpdates(
provider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
You should set MINIMUM_TIME_BETWEEN_UPDATES to time that you want it to be updated frequently and set MINIMUM_DISTANCE_CHANGE_FOR_UPDATES distance the update will change according to your location status.

Related

Getting null location in spite of checking everything

I wish to access user's position using gps system of phone.
In manifest I've included
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I get null location at .appLocationService.getLocation();
public class MainActivity extends AppCompatActivity {
AppLocationService appLocationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(MainActivity.this);
}
public void OpenAddress(View v) {
appLocationService =new AppLocationService(MainActivity.this);
Location location = appLocationService.getLocation();
if (location != null) {
// getting co-ordinates and address
}
else showSettingsAlert();
}
}
I get null location at .getLastKnownLocation(provider);Here i get all locations from all providers. But all seem to return null location
public class AppLocationService extends Service implements LocationListener {
public AppLocationService(){}
Context mcontext;protected LocationManager locationManager;Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
mcontext=context;
}
public Location getLocation() {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) //enabling it
else {
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) continue;
if(bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy())
bestLocation=l;
}
return bestLocation;
}
}
return null;
}
Here is the complete solution. I have wrote it and works pretty good on my device. I have shared on github as well.
Github: click here
MainActivity.java
public class MainActivity extends AppCompatActivity {
AppLocationService mAppLocationService;
boolean mBounded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.callLocation);
}
public void OpenAddress(View view){
Location location = mAppLocationService.getLastKnownLocation();
if (location != null){
Log.e("location","latitude:"+location.getLatitude()+" longtitude"+location.getLongitude());
}else {
Log.e("location","location return null");
}
}
ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
AppLocationService.LocalBinder binder = (AppLocationService.LocalBinder) service;
mAppLocationService = binder.getInstance();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mAppLocationService = null;
}
};
#Override
protected void onStart() {
super.onStart();
Intent i = new Intent(MainActivity.this,AppLocationService.class);
bindService(i,mConnection,BIND_AUTO_CREATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBounded){
unbindService(mConnection);
mBounded = false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/callLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="OpenAddress"
android:text="Location"/>
</android.support.constraint.ConstraintLayout>
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
Location location;
Context mcontext;
protected LocationManager locationManager;
private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
IBinder binder = new LocalBinder();
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class LocalBinder extends Binder{
public AppLocationService getInstance(){
return AppLocationService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public Location getLastKnownLocation() {
final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
Location bestLocation = null;
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
if (Permissions.getInstance(this).checkLocationPermission()) {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
}
} else {
Log.e("check", "Gps is not enable");
}
return bestLocation;
}
#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) {
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shahz.testing">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".AppLocationService"/>
</application>
</manifest>

How to prompt user to enable gps

I am trying to prompt the user to enable gps, i tried many times to resolve issues but not able to clear it.I am new to android can any one please help me........
My mainactivity.java,
public class MainActivity extends AppCompatActivity {
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView.setWebContentsDebuggingEnabled(true);
WebView view = (WebView) this.findViewById(R.id.webView);
view.loadUrl("https://google.com");
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setDatabaseEnabled(true);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setAllowUniversalAccessFromFileURLs(true);
view.getSettings().setAllowContentAccess(true);
view.setWebChromeClient(new WebChromeClient());
view.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
view.setScrollbarFadingEnabled(false);
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setPluginState(PluginState.ON);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setSupportZoom(true);
CheckEnableGPS();
}
private void CheckEnableGPS(){
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.equals("")){
//GPS Enabled
Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider,
Toast.LENGTH_LONG).show();
}else {
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivity(intent);
}
}
}
my androidmanifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.test">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<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>
Implement LocationListener :
#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)
{
if (provider.equals(LocationManager.GPS_PROVIDER))
{
showGPSDiabledDialog();
}
}
Show dialog to open Settings:
public void showGPSDiabledDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("GPS Disabled");
builder.setMessage("Gps is disabled, in order to use the application properly you need to enable GPS of your device");
builder.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), GPS_ENABLE_REQUEST);
}
}).setNegativeButton("No, Just Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
mGPSDialog = builder.create();
mGPSDialog.show();
}
In your onCreate Method call :
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
And override onActivityResult method to test if the user activated GPS correctly.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GPS_ENABLE_REQUEST) {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showGPSDiabledDialog();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Full example :
/**
* Function to check if best network provider
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* */
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?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// 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();
}
Here is the doc : http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ (copied point 7)
Check this official document:
https://developer.android.com/training/permissions/requesting.html
Also, the accepted answer on this thread is the one I used to prompt for storage write access and it works perfectly fine:
Android 6.0 Marshmallow. Cannot write to SD Card
You only need to workout the keywords for location access.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{
protected static final String TAG = "MainActivity";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
Marker mCurrLocationMarker;
GoogleMap mgooglemap;
private LocationManager locationManager;
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(latLng);
// markerOptions.title("Current Position");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// mCurrLocationMarker = mgooglemap.addMarker(markerOptions);
//move map camera
mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
// locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
}
The onProviderDisabled() of the above code will provide you the required flow.
Pls upvote the answer if useful!

how to retrieve location by the NETWORK provider

I am trying to get the location of the device by the network provider.
if i am using GPS is working good.
but when i try to locate it by my provider is all the time return false.
i make sure that in the manifest i have all the permissions that i need:
this is my manifest:
<permission
android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.example.matant.gpsportclient.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.galaxystech.pushnotifications.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and this is my Location class:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating;
private LocationManager locationManager;
private Location currentLoc;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.d("gpsEnabled",String.valueOf(gpsEnabled));
Log.d("networkEnabled",String.valueOf(networkEnabled));
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on settings and make sure your GPS is enabled");
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();
}
}
i found the problem.
in my device setting i need to configure that the device will use only WiFi and cellular networks in order to retrieve the location.

why my gps coordinate is being displayed zero?

I'm making this simple app where when a button is placed users gps location should be displayed and it works fine with emulator but when i try that in a real phone both longitude and latitude are zero.
this is my code:
Main Activiy:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView longS = (TextView) findViewById(R.id.longi);
final TextView latiS = (TextView) findViewById(R.id.lati);
Button btn_show_location = (Button) findViewById(R.id.button1);
btn_show_location.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
longS.setText("Latitude:- " + MyLocationListener.latitude);
latiS.setText("Longitude:- " + MyLocationListener.longitude + '\n');
}
else
{
longS.setText("Please wait");
}
} else {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
}
});
}
MyLocationListener:
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
// loc.getLatitude();
//loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.databasecollect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<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"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
</application>
</manifest>

My location service is not working

My application works as follows:
I have one location listener to every activity
My location listener(which contains location listener) send broadcast on location changed
All activities have broadcast receiver which allows them to set location on map
It has to be working like that, but even my service doesn't start. I'm exhausted writing this app so I place my code here, maybe I overlooked some simple issue. I need help with that topic:
GPS Service:
// package and imports
public class GeoService extends Service {
LocationListener GPSLocationListener, NetworkLocationListener;
LocationManager locationManager;
private IBinder mBinder;
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getPosition();
return Service.START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
getPosition();
if (mBinder == null) mBinder = new GeoBinder();
return mBinder;
}
private void getPosition() {
GPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendPosition(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), provider + " is now disabled. Turn it on to find better GPS position.", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), provider.toUpperCase() + " is now enabled. Waiting for better position..", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case 0:
case 1:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, NetworkLocationListener);
break;
case 2:
locationManager.removeUpdates(NetworkLocationListener);
break;
}
}
};
NetworkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendPosition(location);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, GPSLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, NetworkLocationListener);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) alert();
}
private void alert() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Internet connection and GPS are not avaiable!.").setCancelable(false).setTitle("No location provider!").setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Change settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
}
}).create().show();
}
void sendPosition(Location location) {
Intent gpsPosition = new Intent();
gpsPosition.putExtra("location", location);
gpsPosition.setAction(Context.LOCATION_SERVICE);
sendBroadcast(gpsPosition);
}
public GeoPoint getGeoPoint(final Location loc) {
int lat = (int) (loc.getLatitude() * 1e6);
int lon = (int) (loc.getLongitude() * 1e6);
return new GeoPoint(lat, lon);
}
public GeoPoint getLastLocation() {
GeoPoint lastKnownPoint;
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation == null) lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastKnownLocation != null) lastKnownPoint = getGeoPoint(lastKnownLocation);
else lastKnownPoint = new GeoPoint((int) (51.110582 * 1E6), (int) (17.031509 * 1E6));
return lastKnownPoint;
}
#Override
public void onDestroy() {
locationManager.removeUpdates(GPSLocationListener);
locationManager.removeUpdates(NetworkLocationListener);
}
public class GeoBinder extends Binder {
public GeoService getService() {
return GeoService.this;
}
}
}
One of Activities: (I tried to start or bind service but none method seems to be working).
// package and imports
public class ShareLocationActivity extends MapActivity {
private final int PICK_CONTACT = 123;
MapView.LayoutParams mapMarkerParams;
MapController mapController;
Location lastLocation;
ImageView mapMarker;
GeoPoint current;
MapView map;
private ServiceConnection mConnection;
GeoService mService;
boolean mBound = false;
BroadcastReceiver locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setPosition((Location) intent.getParcelableExtra("location"));
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_location);
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
GeoBinder binder = (GeoBinder) service;
mService = binder.getService();
mBound = true;
mapController = map.getController();
mapController.setCenter(mService.getLastLocation());
mapController.setZoom(17);
}
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
Intent intent = new Intent(this, GeoService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
map = (MapView) findViewById(R.id.shareMapView);
map.setBuiltInZoomControls(true);
map.setSaveEnabled(true);
mapMarker = new ImageView(getApplicationContext());
mapMarker.setImageResource(android.R.drawable.presence_online);
Button share = (Button) findViewById(R.id.shareActivityButton);
share.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent contacts_intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contacts_intent, PICK_CONTACT);
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(Context.ACTIVITY_SERVICE);
registerReceiver(locationReceiver, filter);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
if (current != null) sendSms(data);
else Toast.makeText(getApplicationContext(), "No GPS data yet..", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBound) {
Intent intent = new Intent(this, GeoService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
};
#Override
protected void onPause() {
map.removeAllViews();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
map.removeAllViews();
}
void setPosition(Location location) {
map.removeAllViews();
current = mService.getGeoPoint(location);
mapMarkerParams = new MapView.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, current, MapView.LayoutParams.TOP_LEFT);
map.addView(mapMarker, mapMarkerParams);
mapController.setCenter(current);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
And to be sure Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gps.counter"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.location" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application
android:icon="#drawable/ico"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<uses-library android:name="com.google.android.maps" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SaveLocationActivity" />
<activity android:name=".ShareLocationActivity" />
<activity android:name=".RecordTrackActivity" />
<activity android:name=".SettingsActivity" />
<service
android:name=".GeoService"
android:enabled="true" />
</application>
</manifest>
The solution is to keep service and activity which uses it in one package.
It is small issue but can be big problem for someone.

Categories

Resources