Android Service access to static member of another class - android

I have a problem with my android service. In the "onLocationChanged", i want to access a static member of my class "Device".
I start my service with :
Intent i = new Intent(this, LocationService.class);
startService(i);
This is my class LocationListener with the service:
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Device.getLocationType().setLocationData(location);
}
#Override
public void onProviderDisabled(String provider)
{
//...
}
#Override
public void onProviderEnabled(String provider)
{
//...
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
//...
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStartCommand");
return START_STICKY;
}
#Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE,
mLocationListeners[1]);
Log.d(TAG, "try");
} catch (java.lang.SecurityException ex) {
Log.d(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE,
mLocationListeners[0]);
Log.d(TAG, "try2");
} catch (java.lang.SecurityException ex) {
Log.d(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
My class Device
public class Device {
private static LocationType locationType;
//...
}
And the class LocationType
public class LocationType {
private Location location;
public LocationType(){
//...
}
Location getLocationData() {
return location;
}
void setLocationData(Location location) {
this.location = location;
}
}
My application failed because, i don't have the right to access static member from service? How can i access this static member?
Thanks a lot for your answer.

You use Device.getLocationType() are you sure this method is also static ? So either make it static or make locationType public and access it directly.
Whether you'd want to is another thing entirely.
Also, try to replace :
private static LocationType locationType;
with :
private static LocationType locationType = new LocationType();

You field is private
private static LocationType locationType;
Make it public and it should be accessible
public static LocationType locationType;
If that isn't desired you should at least make a static getter which is either public or package private. If it's package private, make sure both classes are within the same package.

My object "locationType" is always defined to null... In my MainActivity, i call the method Device.init(...). This method create the object LocationType in the static member.
public class Device {
private static LocationType locationType;
public static void init(...){
Device.locationType = new LocationType(...);
if(Device.locationType != null){
Intent i = new Intent(activity, LocationService.class);
activity.startService(i);
}
}
My service is launched, but in the service method "onLocationChanged", the Device.locationType is null.

Related

Making a backend API call from a service

I have a service that runs in both foreground and background to get the user location at all times, I simply use a LocalBroadCastManager to send the location from the foreground to an activity in my application and then start my API call.
How to achieve the same when the service is running in the background or when the application is closed.
The service:
public class LocationService extends Service {
private static final String TAG = "LocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1000f;
private HandlerThread mHandlerThread;
private Handler mHandler;
private final IBinder mBinder = new MyLocalBinder();
Location mLastLocation;
private class LocationListener implements android.location.LocationListener
{
public LocationListener(String provider)
{
Helper.showLog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Helper.showLog(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
sendBroadcast();
}
#Override
public void onProviderDisabled(String provider)
{
Helper.showLog(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Helper.showLog(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Helper.showLog(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
mHandlerThread = new HandlerThread("LocalServiceThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
sendBroadcast();
}
public void postRunnable(Runnable runnable) {
mHandler.post(runnable);
}
public class MyLocalBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
#Override
public void onDestroy()
{
Helper.showLog(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listeners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Helper.showLog(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private void sendBroadcast(){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("latitude",mLastLocation.getLatitude() );
intent.putExtra("longitude",mLastLocation.getLongitude() );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}

using Service in android application

this code is work with me to take the coordination even if the application is not in use but when i switch of my phone then open my phone again it is not working in the background i need it continue working in the background. even if the user mobile pone is switched off and then it is opened again
public class Check2 extends Service
{
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
private static final String TAG = "GPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000*6;
private static final float LOCATION_DISTANCE = 0f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
double lat = mLastLocation.getLatitude();;
double lon = mLastLocation.getLongitude();
Toast.makeText(getApplicationContext(), "Lat: "+lat+" Long: "+lon, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
LocationManager loc;
loc=(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =new LocationListener(TAG);
Location location ;
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
// location = listener.mLastLocation;
location= loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
listener.onLocationChanged(location);
Log.d("is work","here");
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
location= loc.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
listener.onLocationChanged(location);
Log.d("is work", "here");
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
Create a Broadcast receiver to listen for Boot Complete event
Check this link for tutorials
Broadcast receiver for Boot Action
1 to Vivek, but also you should start your service in another process from your application. For example,
<< service
android:name=".TweetCollectorService"
android:process=":remote">
Then in your service you should add BroadcastReceiver to receive intent BOOT_COMPLETE. If you want this service to keep running no matter what, consider replacind startService method with startForeground

Android Is it a good practice to use LocationListener in a IntentService?

My app has a widget and shows information depending on the location of the device.
I would like to get the location by using a IntentService, because it destroys itself after the job is done, however the algorythm executes the
#Override
protected void onHandleIntent(Intent intent)
method and finishes. so there is no time to listen for some locations and give the info back.
is it possible to let the LocationListener wait until the
#Override
public void onLocationChanged(Location location) {
is called?
how to use properly the Looper in the
LocationManager.requestLocationUpdates(
method?
here the entire code for the IntentService:
public class GetLocation extends IntentService {
public GetLocation() {
super("GetLocation");
// TODO Auto-generated constructor stub
}
private static final String TAG = "GetLocation";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private ResultReceiver resultReceiver;
public static final String RECEIVER = "receiver";
public static final String GPS = "gps";
private int result = Activity.RESULT_CANCELED;
public static String RESULT = "result";
Location mLastLocation;
private class LocationListener implements android.location.LocationListener {
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
result = Activity.RESULT_OK;
publishResults(new double[] { mLastLocation.getLatitude(),
mLastLocation.getLongitude() }, result);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
// new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER) };
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.e(TAG, "onHandleIntent");
resultReceiver = intent.getParcelableExtra(RECEIVER);
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
Log.i(TAG, "remove location listners");
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
}
}
private void publishResults(double[] gps, int result) {
Bundle bundle = new Bundle();
bundle.putDoubleArray(GPS, gps);
bundle.putInt(RESULT, result);
resultReceiver.send(Activity.RESULT_OK, bundle);
}
}
EDIT:
I would like to add the final code for the Service that gives the coordinates to a receiver:
However, it is only the gps provider working, the network is ignored on the device (everything is activated in the settings)
public class LocationGetter extends Service {
private static final String TAG = "LocationGetter";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private ResultReceiver resultReceiver;
public static final String RECEIVER = "receiver";
public static final String GPS = "gps";
private int result = Activity.RESULT_CANCELED;
public static String RESULT = "result";
Location mLastLocation;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.e(TAG, "onStartCommand");
resultReceiver = intent.getParcelableExtra(RECEIVER);
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
return super.onStartCommand(intent, flags, startId);
}
private class LocationListener implements android.location.LocationListener {
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
result = Activity.RESULT_OK;
publishResults(new double[] { mLastLocation.getLatitude(),
mLastLocation.getLongitude() }, result);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER) };
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
}
}
private void publishResults(double[] gps, int result) {
Bundle bundle = new Bundle();
bundle.putDoubleArray(GPS, gps);
bundle.putInt(RESULT, result);
resultReceiver.send(Activity.RESULT_OK, bundle);
}
}
You had select the wrong way to go - you should use Service to listen for Location updates, because Service will not be closed after it's code have been executed.
Another way - is to subscribe some service component to Location updates via AndroidManifest.xml by defining proper IntentFilter. In this situation - it can be an IntentService, as only it's OnReceive() method will be executed.

android onServiceConnected in bound service is never called

I am trying to bound a service to my activity and get location values from it.
I have the following service:
GPSService.java
public class GPSService extends SensorElement {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public GPSService getService() {
// Return this instance of GPSService so clients can call public
// methods
return GPSService.this;
}
}
private static final String TAG = "GPSServive";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private Location location;
private boolean canGetLocation;
private double latitude;
private double longitude;
private double accuracy;
private long timestamp;
public SensorType type = SensorType.SOFTWARE_SENSOR;
public SensorName name = SensorName.GPS_SENSOR;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER) };
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
if (!isNetworkAvailable() && !isGPSAvailable()) {
// no network provider is enabled
setCanGetLocation(false);
} else if (isNetworkAvailable()){
setCanGetLocation(true);
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, mLocationListeners[1]);
location = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
timestamp = System.currentTimeMillis();
}
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
} else if (isGPSAvailable()) {
setCanGetLocation(true);
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, mLocationListeners[0]);
location = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
timestamp = System.currentTimeMillis();
}
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG,
"network provider does not exist, " + ex.getMessage());
}
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
}
}
private boolean isNetworkAvailable() {
return mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isGPSAvailable() {
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public double getAccuracy() {
return accuracy;
}
public long getTimestamp() {
return timestamp;
}
public SensorType getType() {
return type;
}
public void setType(SensorType type) {
this.type = type;
}
public SensorName getName() {
return name;
}
public void setName(SensorName name) {
this.name = name;
}
public boolean isCanGetLocation() {
return canGetLocation;
}
public void setCanGetLocation(boolean canGetLocation) {
this.canGetLocation = canGetLocation;
}
}
This is the abstract class that the GPSService extends. The goal for this is to have something that generalizes a sensor, gps sensor accelerometer sensor, whatever sensor.
SensorElement.java
public abstract class SensorElement extends Service{
protected SensorType type;
protected SensorName name;
#Override
public abstract IBinder onBind(Intent arg0);
#Override
public int onStartCommand(Intent intent, int flags, int startId){
return super.onStartCommand(intent, flags, startId);
}
#Override
public abstract void onCreate();
#Override
public void onDestroy(){
super.onDestroy();
}
}
Now i have my activity that is trying to bind to the GPSService.
InSituApp.java
public class InSituApp extends Activity{
GPSService gpsService;
boolean mBound = false;
public Button buttonGPS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, GPSService.class));
//startService(new Intent(this, MyService.class));
// buttonGPS = (Button) findViewById(R.id.button1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("ENTERED IN ONSTART");
// Bind to GPSService
Intent intent = new Intent(this, GPSService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Called when a button is clicked (the button in the layout file attaches to
* this method with the android:onClick attribute) */
public void onButtonClick(View v) {
System.out.println("DIDNT ENTERED IN BOUND");
if (mBound) {
// Call a method from the LocalService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
System.out.println("ENTERED IN BOUND");
double latitude = gpsService.getLatitude();
double longitude = gpsService.getLongitude();
double accuracy = gpsService.getAccuracy();
long timestamp = gpsService.getTimestamp();
Toast.makeText(this, "latitude: " + latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "longitude: " + longitude, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "accuracy: " + accuracy, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "timestamp: " + timestamp, Toast.LENGTH_SHORT).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
System.out.println("ENTERED IN ONSERVICE CONNECTED");
LocalBinder binder = (LocalBinder) service;
gpsService = binder.getService();
System.out.println("GPSService: "+gpsService!=null);
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
System.out.println("ENTERED IN ONSERVICE DISCONNECTED");
}
};
}
This code never calls the onServiceConnected method inside mConnection. What is wrong in here? The bindService call in onStart returns false. Why is that?
EDIT:
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="main.inSituApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name="main.inSituApp.InSituApp" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GPSService" />
<service android:name=".FileObservingService" />
</application>
</manifest>
I found the solution.
The problem is in the manifest file where the service must be the total path of the package.
in my case sensors.GPSService
Hope it helps someone

Gps service - couldn't retrieve a location

I am newbie. I wrote a class, that implements service and uses gps, but location allways null. All needed permissions are wrote and service is normally starting, i could bind to it, but retrieved location is allways null and it never goes in onLocationChanged(Location location). Can anybody help, please?
public class GPSService extends Service {
private static final String TAG = "GPS_SERVICE";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
Location currentLocation;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
if (location != null){
mLastLocation.set(location);
currentLocation = mLastLocation;
}
}
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private IBinder mBinder = new GPSServiceBinder();
public class GPSServiceBinder extends Binder {
public GPSService getServerInstance() {
return GPSService.this;
}
}
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
public IBinder onBind(Intent intent) {
return mBinder;
}
int minTime = 6000;
float minDistance = 15;
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
public Location getLocation()
{
return currentLocation;
}
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
If you're using emulator with 2.3 version of Android then there is a bug. I've just recently faced with it. You can install 2.3 x86 emulator in this case. It works fine.

Categories

Resources