将Location对象从Service传递到Activity中的处理程序

时间:2011-03-29 20:16:39

标签: android location handler

我正在尝试创建一个在后台运行的服务,并在位置发生变化时/或当用户位于特定位置时通知活动。

我还在学习Android编程,我有点不知道如何将Location对象传递给Activity。这是我的代码:

public class MyActivity extends Activity {  
...  
@Override  
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
startService(new Intent(MyActivity.this,LocationService.class));
}  
...    
 Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  
            Location loca=msg.obj;         //I cannot do this,or can I??    
                float lat = (float) (loca.getLatitude());   
              }  
           };  
}

public class LocationService extends Service {   
...




public void updateLocation(Location loc) {                  
            Message msg = Message.obtain();
            msg.obj = loc;      
            messageHandler.sendMessage(msg);     
        }    
}    

1 个答案:

答案 0 :(得分:2)

除了不适当地投射之外,我没有看到任何问题,试试这个..

Location loca = (Location)msg.obj;

你不能在没有强制转换的情况下将超类分配给子类,但是你可以反过来。