Problems closing Acitivity after GPS location is retrieved using another Class
-
13-11-2019 - |
Question
Situation is this:
- Activity A calls
getLocation()
method from Class B.
Class B handles obtaining GPS locations.
2 Activity A should finish once Class B has finished retrieving GPS location.
Activity A calls something like:
B.getLocation()
this.finish()
i.e. gets the location using method from B and then finishes itself. In reality, A closes before B has a chance to get the location.
How do I structure this correctly so that A waits till B has finished?
Solution
The design here is lacking. In fact, you can't just call one Activity
's method for the other one, since only one Activity
can be in foreground at the moment. Your activities should communicate using Intents
. Here's how it should work:
Activity A
startsActivity B
using anIntent
Activity B
gets location and returns it toActivity A
, using thesetResult()
methodActivity A
reads the result fromActivity B
in itsonActivityResult()
methodActivity A
finishes
This feels like a better implementation. Actually, if Activity B
does just get location, you can simple implement it as a Service
and bind it to Activity A
. Hope this helps.
OTHER TIPS
ok you need to do some callback Mechanism, if you are familiar with Basic Java.. Here I am just trying to give you an overview of CallBack in Java...
//Here is you class B :
class ClassB {
interface ILocationListerner {
void setLocations(float lat, float long);
}
ILocationListerner mLocationListener = null;
/// Here is your static method that set Listerner and call by Activity A
public void static setLocationListerner(ILocationListerner listener){
this.mLocationListener = listener;
}
//Gel loaction method.
public static void getLocation(){
////
...
////
mLocationListener.setLocation(lat,lng);
}
}// ClassB ends here
/// Activity A
class ActivityA extends Activity {
onCreate(){
ClassB.setLocationListerner(new ILocationListerner {
@Override
void setLocations(float lat, float long){
/// do your stuff and call finish();
}
} );
ClassB.getLocation();
}
}
}
Hope you understand this...