将位置对象从服务传递到活动中的处理程序
我正在尝试创建一个在后台运行的服务,并在位置发生更改/或用户位于特定位置时通知活动。
我仍在学习 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);
}
}
I am trying to create a service which would run in the background and inform an Activity whe the location has changed/ or when the user is in a particular location.
I am still learning Android programming and I am a bit stuck with not understanding how I can pass a Location object to the Activity. Here is what my code looks like:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
乍一看,除了不进行适当的转换之外,我没有看到任何问题,请尝试这个。
您不能在不进行转换的情况下将超类分配给子类,但是您可以反之亦然。
I don't see any issues at first glance aside from not casting appropriately, try this..
You can't assign a super class to a subclass without casting, you can however go the other way around.