Search code examples
androidlocationandroid-locationlocationlistener

Can we write MyLocationListener outside the xxxActivity class?


Can i write MyLocationListener outside the MainActivity class? as the following example

MainActivity.class

public class MainActivity extends Activity{

    @Override
    ..onCreate(){
    .
    .
    loclis = new MyLocationListener(this); // Can i use it this way? 
    //if so, where is the best place to declare this line. 

    }
}

MyLocationListener.class

public class MyLocationListener implement LocationListener{
..
.//Constructor of MyLocationListener
}

Thanks you for you help


Solution

  • Yes, you can declare a stand-alone class as a location listener. If you do, though, you'll probably want to have a mechanism of allowing your listener to call back into your activity if the location changes (or else your activity will never know that you got a location update):

    public class MyLocationListener implements LocationListner{
    
       private SomeInterface owner;
    
       public MyLocationListener(SomeInterface owner){
           this.owner = owner;
    } 
    
    }
    

    Then your activity could look like:

    public class MainActivity extends Activity implements SomeInterface{
    
        private LocationListner locListener;
        public void onCreate(Bundle savedInstanceState){
            locListener = new MyLocationListener(this);
        }
    
    }