onlocationchanged not called - android

When I test the application using the Eclipse DDMS - it works, onlocationchanged called
but when I install the app on your tablet - nothing
my source
public class Fragment_1 extends Fragment{
final String LOG_TAG = "myLogs";
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
private String bestProvider;
private Context contextActivity;
private LocationManager locationManager;
private MyLocationListener locationListener;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
contextActivity = getActivity();
locationManager = (LocationManager) contextActivity.getSystemService(contextActivity.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
bestProvider = locationManager.getBestProvider(crit, false);
locationListener = MyLocationListener.createMyLocationListener(this);
locationManager.requestLocationUpdates(
bestProvider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
locationListener);
}
and my class MyLocationListener
ublic class MyLocationListener implements LocationListener {
private Fragment_1 fragment;
private static MyLocationListener myLocationListener;
public MyLocationListener(Fragment_1 fragment_1) {
// TODO Auto-generated constructor stub
fragment = fragment_1;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(fragment.getActivity() !=null) {
TextView textViev = (TextView)fragment.getActivity().findViewById(R.id.textView1);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
textViev.setText(message);}
}
public static MyLocationListener createMyLocationListener (Fragment_1 fragment_1) {
if (myLocationListener == null) {
myLocationListener = new MyLocationListener(fragment_1);
} else {
myLocationListener.setFragment(fragment_1);
}
return myLocationListener;
}
private void setFragment (Fragment_1 fragment){
this.fragment = fragment;
}
}
and permission in the manifest
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

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>

GPS coordinates are not updating

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.

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.

Stop Location Service

whenever I try to stop my location service on android I get a NullPointerException. anyone has some tips on how to do it? I want to implemented on some activities onstop() and ondestroy() methods. Here is my service code:
LocationService.Java
package com.storetab;
public class LocationService extends Service {
static LocationManager locationManager;
static Location lastknown;
final static String MY_ACTION = "MY_ACTION";
static LocationListener ll;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
final Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
locationManager.getBestProvider(criteria, true);
ll = new MyLocListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
lastknown = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("Teste","lastknown");
Intent intent1 = new Intent();
intent.putExtra("location1", lastknown);
intent.setAction(MY_ACTION);
sendBroadcast(intent1);
Log.d("broadcastlast","lastknown");
return START_STICKY;
}
private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Log.d("1Provider DIsabled", "Provider Disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("1Provider Enabled", "Provider Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("1Provider Changed", "Service Status Changed");
}
}
#Override public void onDestroy() {
locationManager.removeUpdates(ll);
};
}
In your onStartCommand() you have this code:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
This creates a local variable called locationManager, which hides the class variable you have declared above that at the top of the class:
static LocationManager locationManager;
The static class variable locationManager never gets set to anything, so it is null in onDestroy().
To fix that, just change it to this in onStartCommand():
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

Force close when start GPS service

I have a problem when the service is started: the appliaction shows a force close message.
my startservice in the main activity looks like this:
startService(new Intent(Main.this,GPSService.class));
GPSService.class
public class GPSService extends Service implements LocationListener {
LocationManager locationManager;
double x1,x2;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location loc)
{
x1=loc.getAltitude();
x2=loc.getLatitude();
}
public void onProviderEnabled(String s){
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onProviderDisabled(String s){
//locationManager.removeUpdates(this);
//x1=0;
// x2=0;
}
public void onStatusChanged(String s, int i, Bundle b){}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
}
You need to give following permissions in androidManifest.xml
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES">

Categories

Resources