How to Restart a service after app is killed - android

I have to get location updates from location manager. I want the service remains continue if app is killed.
I have the following service class. I am using broadcast receiver. In onTaskRemove() method i send broadcast. in receiver class I restart the service, but not restarted. Please help. Thanks.
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
public GoogleService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("ChangeStatus"));
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*rootIntent = new Intent("ChangeStatus");
rootIntent.putExtra("action", "statusChange");
sendBroadcast(rootIntent);*/
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("ChangeStatus"));
}
#SuppressLint("MissingPermission")
private void fn_getlocation(){
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable){
}else {
if (isNetworkEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
if (isGPSEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class TimerTaskToGetLocation extends TimerTask{
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
**my Reciver class is**
public class RestartServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), GoogleService.class));
}
}
my Manifest
<service android:name=".GoogleService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false"
></service>
<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="ChangeStatus" >
</action>
</intent-filter>
</receiver>
What i am doing wrong .

Use Pending Intent to get LocationUpdates using service upto android 7.0 above use you have to use Broadcast receiver:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if (result != null) {
List<Location> locations = result.getLocations();
Log.d("servicelocation","*******lastupdate "+result.getLastLocation());
Log.d("servicelocation","******* "+locations.size()+
"\n"+locations.get(locations.size()-1).getLatitude() +" " +
"lng "+locations.get(locations.size()-1).getLongitude());
Toast.makeText(getApplicationContext(),"Service Stared "+locations.size(),Toast.LENGTH_SHORT).show();
}
}
}else {
Log.d("serviceintentvalues","********");
}
return START_STICKY;
}
Here complete reference given be google samples : https://github.com/googlesamples/android-play-location
it's working well for me check...

Related

how to send user location data to server every 5 second even app is closed?

How to send user location data to server every five second using restful API even app is closed in android?
Please help me
you can create a background service that it works when user lock screen or close your app from background
you must create service with this way:
first create a Service class like this:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks {
public static double latitude;
public static double longitude;
private int retryGPS = 0;
private int retryNetwork = 0;
private Handler handler;
private Runnable runnable;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
};
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1;
private static final String TAG = "LocationService";
#Override
public void onCreate() {
buildGoogleApiClient();
initializeLocationManager();
locationRequest();
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
sendLocation();
}
};
sendLocation();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private void locationRequest() {
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, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
}
private void sendLocation() {
//TODO: you can use location here
handler.postDelayed(runnable,5000);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
try {
Thread.sleep(3000);
onConnected(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
if (mLocationManager != null) {
for (LocationListener mLocationListener : mLocationListeners) {
try {
mLocationManager.removeUpdates(mLocationListener);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onDestroy();
}
private class LocationListener implements android.location.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
Location mLastLocation;
public LocationListener(String provider) {
Log.d(TAG, "LocationListener: " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(final Location location) {
mLastLocation.set(location);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d(TAG, "onLocationChanged: { latitude: " + latitude + " ,longitude: " + longitude + " , accuracy: " + location.getAccuracy() + " }");
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged: " + status);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
}
}
}
then register service in manifest:
<service
android:name=".service.LocationService"
android:enabled="true"
android:process=":process" />
then start service from any activity or fragment :
public static void mStopService(Context context) {
context.stopService(new Intent(context, LocationService.class));
}
public static void mStartService(Context context) {
context.startService(new Intent(context, LocationService.class));
}
if you want to make your code run even when the app is closed you need to use services, services can run in the background even if the app is closed, and you may need to use a broadcast receiver with the service to keep running it every time it finishes.
this is the Service:
public class myService extends Service {
public static int counter = 0;
public myReceiver myReceiver = new myReceiver();
#Override
public void onCreate() {
super.onCreate();
//this line register the Receiver for the first time
myService.this.registerReceiver(myReceiver, new IntentFilter("com.example.myApp"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Here you have to put the code that gets the location and send it
}
#Override
public void onDestroy() {
super.onDestroy();
//here you sent a broadcast message to start the reciever
//note that the broadcast message that you send has to be unique writing you package name will be fine ex: com.example.myApp
Intent sendBroadCast = new Intent("com.example.myApp");
sendBroadcast(sendBroadCast);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
and this is the broadcast receiver:
public class myReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if("com.example.myApp".equals(intent.getAction())){
//the handler is used as a timer here
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent myServ = new Intent(context, myService.class);
try {
context.startService(myServ);
}catch (Exception e){
}
}
},5000);
}
}
}

Why location service stopped to send location updates when i locked phone

I have created background service to get user location periodically and send it to server like this :`
public class SyncDataToServerService extends Service {
private static final String TAG = "SyncDataToServerService";
private ServerCall serverCall;
private SharedPreferences tempPref2;
private Timer timer;
LocationManager locationManager;
UtilityClass utilityClass;
PowerManager.WakeLock wakeLock;
PowerManager powerManager;
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
serverCall = new ServerCall(this);
timer = new Timer();
utilityClass = new UtilityClass(this);
tempPref2 = getSharedPreferences(getString(R.string.temp_pref_name_2), Context.MODE_PRIVATE);
}
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e(TAG, "onStartCommand");
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager != null)
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyApp::MyWakelockTag");
wakeLock.acquire();
//initialize and start Location service
startLocation();
//initialize and start the TimerTask's job
startTimer();
return START_STICKY;
}
#SuppressLint("MissingPermission")
private void startLocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager != null)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
10, new MyLocationListener());
if (locationManager != null)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
10, new MyLocationListener());
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
if (locationManager != null)
locationManager.removeUpdates(new MyLocationListener());
super.onDestroy();
}
private void syncPath(Location mLocation) {
Log.w(TAG, "Location: " + mLocation + " Latitude: " + mLocation.getLatitude() + " & Longitude: "
+ mLocation.getLongitude());
if (tempPref2.getString(getString(R.string.attendance_key), "").equalsIgnoreCase("present")) {
serverCall.sendEmpPath(mLocation);
}
}
private void startTimer() {
TimerTask timerTask = new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void run() {
if (utilityClass.isInternetConnected()) {
if (serverCall != null) {
if (serverCall.requestQ.size() > 0)
Log.e(TAG, "Request queue size ==" + serverCall.requestQ.size());
serverCall.syncData();
}
}
}
};
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000);
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
Intent intent1 = new Intent("com.example.mc_project");
intent1.putExtra("location", location);
sendBroadcast(intent1);
if (location.getAccuracy() < 25)
syncPath(location);
wakeLock.release();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}`
everything working fine but when i lock my phone it stop to send location updates. i have read that it is because of system sleep and have to use wake lock but it also not working.And when i unlock phone it suppose to start to send location updates but this also not happening.My service do not stop,it always in running state.Please help where i am doing wrong or missing something.
you should use foreground service and put location update code inside it .
os stops background service any time power is off

Fragment BroadCast receiver not working

I'm making an app where I need to get constant location updates from a Service on a fragment, the problem is that the fragment is not getting the updates and I'm not sure what is the problem, here is the service:
public class GPService extends Service
{
private LocationManager locMan;
private Boolean locationChanged;
private Handler handler = new Handler();
static final int REQUEST_LOCATION = 1;
public static Location curLocation;
public static boolean isService = true;
public LocalBroadcastManager broadcast;
LocationListener gpsListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (curLocation == null) {
curLocation = location;
locationChanged = true;
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",curLocation.getLatitude());
intent.putExtra("latitud",curLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
locationChanged = false;
return;
}else
locationChanged = true;
curLocation = location;
if (locationChanged)
locMan.removeUpdates(gpsListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,Bundle extras) {
}
};
#Override
public void onCreate() {
super.onCreate();
curLocation = getBestLocation();
if (curLocation == null)
Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
else{
//Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
}
isService = true;
broadcast= LocalBroadcastManager.getInstance(this);
}
final String TAG="LocationService";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent i, int startId){
handler.postDelayed(GpsFinder,1);
}
#Override
public void onDestroy() {
handler.removeCallbacks(GpsFinder);
handler = null;
Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
isService = false;
}
public IBinder onBind(Intent arg0) {
return null;
}
public Runnable GpsFinder = new Runnable(){
public void run(){
Location tempLoc = getBestLocation();
if(tempLoc!=null)
curLocation = tempLoc;
tempLoc = null;
handler.postDelayed(GpsFinder,1000);
}
};
private Location getBestLocation() {
Location gpslocation = null;
Location networkLocation = null;
if(locMan==null){
locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
}
try {
if ( ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",gpslocation.getLatitude());
intent.putExtra("longitud",gpslocation.getLongitude());
Log.wtf("COORDENATES TO SEND",gpslocation.getLatitude()+" "+gpslocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
Log.wtf("LAS COORDENADAS a enviar SON",networkLocation.getLatitude()+" "+networkLocation.getLongitude());
intent.putExtra("latitud",networkLocation.getLatitude());
intent.putExtra("longitud",networkLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
}
The service is initiated in the activity like this
startService(new Intent(this, GPService.class));
In the fragment this is how I create it and register it
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
receiver= new GPSReceiver();
//this.getActivity().registerReceiver(receiver, new IntentFilter());
db=Database.getInstance(this.getContext());
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
getActivity().registerReceiver(receiver,filter);
}
#Override
public void onPause() {
getActivity().unregisterReceiver(receiver);
super.onPause();
}
Finally this is the reciever in the Fragment, I can't get it to get the info from the service, any ideas? I don't know what I'm doing wrong.
private class GPSReceiver extends BroadcastReceiver {
private LatLng changed;
public GPSReceiver()
{
changed= new LatLng(0,0);
}
#Override
public void onReceive(Context context, Intent intent) {
Log.wtf("RECIEVE", "IT IS IN BROADCAST");
if (intent.getAction().equals("GPSLocationUpdates"))
{
Log.wtf("RECIEVE1", "INTENT ARRIVES");
double lat= intent.getDoubleExtra("latitud",1);
double longi= intent.getDoubleExtra("longitud",1);
changed= new LatLng(lat,longi);
}
// String text = intent.getStringExtra("position");
}
public LatLng getChanged()
{
return changed;
}
}
The service seems to be working fine, I can see the coordinates in the console being send.
You're not registering you BroadcastReceiver to the LocalBroadcastManager. You're registering it to the global broadcast manager, but sending on the local.
Change:
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,filter);
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onPause();
}

Android Location update is happening twice

I want to run location update as a service. Now I can able to run the service correctly but the location updation is happening twice, Here is the code,
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service
android:name=".services.LocationService"
android:icon="#drawable/ic_location"
android:label="Location Service">
<intent-filter>
<action android:name="android.service.notification.service" />
</intent-filter>
</service>
In the Activity Class we are using startLocationService() to start the service and stopLocationService() to stop the service, Also created a Broadcast Receiver to get the location updation on the Activity Calss.
private BroadcastReceiver broadcastReceiver;
private Intent mLocationServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigtaion_drawer);
AppController.getInstance().activityResumed();
broadcastReceiver = createBroadcastReceiver();
registerReceiver(broadcastReceiver, new IntentFilter(getPackageName()));
if (!Permissions.hasLocationPermission(this)) {
Permissions.requestLocationPermission(this, PermissionKeys.LOCATION_REQUEST_HOME_ON_RESUME);
} else
startLocationService();
}
private BroadcastReceiver createBroadcastReceiver() {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(LocationService.LOCATION_UPDATED)) {
Bundle b = intent.getExtras();
if (b != null) {
Location mCurrentLocation = (Location) b.get(LocationService.LOCATION_UPDATED);
}
}
}
};
}
//Function To Start the Service
public void startLocationService() {
if (mLocationServiceIntent == null)
mLocationServiceIntent = new Intent(this, LocationService.class);
startService(mLocationServiceIntent);
}
//Function To Stop the Service
public void stopLocationService() {
if (mLocationServiceIntent != null)
stopService(mLocationServiceIntent);
}
LocationService.java
public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String LOCATION_UPDATED = "LocationUpdated";
public static final String LATITUDE = "Latitude";
public static final String LONGITUDE = "Longitude";
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private static final String TAG = "###LocationService:: ";
private static final int LOCATION_INTERVAL = 15000;
private static final int FASTEST_INTERVAL = 10000;
private static final float LOCATION_DISTANCE = 7f;
#Override
public void onCreate() {
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(LOCATION_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//mLocationRequest.setSmallestDisplacement(10.0f); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connected");
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connection suspended");
}
protected void startLocationUpdates() {
Log.e(TAG, "Start Location Updates");
try {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
} catch (IllegalStateException e) {
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "Location Changed : " + location.getLatitude() + "," + location.getLongitude());
Intent intent = new Intent(getPackageName());
intent.putExtra(LOCATION_UPDATED, location);
sendBroadcast(intent);
}
}
/* 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);
return START_STICKY;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed:: "+connectionResult.getErrorMessage());
}
}
I have fixed this issue by adding a condition checking before start the service,
My updated startLocationService() function is like,
//Function To Start the Service
public void startLocationService() {
if (mLocationServiceIntent == null)
mLocationServiceIntent = new Intent(this, LocationService.class);
if(!isServiceRunning(HomeScreenActivity.this, LocationService.class)) {
startService(mLocationServiceIntent);
}
}
Here is the function to check if the service is already running or not.
//This function is to check the service is already running or not
public boolean isServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.e("ServiceRunning", serviceClass.getSimpleName() + " is alredy running");
return true;
}
}
return false;
}

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

Categories

Resources