我们可以在xxxActivity类之外编写MyLocationListener吗?

时间:2011-11-30 15:56:52

标签: android location android-location locationlistener

我可以在MainActivity类之外编写MyLocationListener吗?如下例

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
}

谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

是的,您可以将独立类声明为位置侦听器。但是,如果您这样做,您可能希望有一种机制,允许您的监听器在位置发生变化时回调您的活动(或者您的活动永远不会知道您有位置更新):

public class MyLocationListener implements LocationListner{

   private SomeInterface owner;

   public MyLocationListener(SomeInterface owner){
       this.owner = owner;
} 

}

然后您的活动可能如下:

public class MainActivity extends Activity implements SomeInterface{

    private LocationListner locListener;
    public void onCreate(Bundle savedInstanceState){
        locListener = new MyLocationListener(this);
    }

}