将位置对象从服务传递到活动中的处理程序

发布于 2024-10-27 11:12:06 字数 939 浏览 1 评论 0原文

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

我仍在学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房的律动 2024-11-03 11:12:06

乍一看,除了不进行适当的转换之外,我没有看到任何问题,请尝试这个。

Location loca = (Location)msg.obj;

您不能在不进行转换的情况下将超类分配给子类,但是您可以反之亦然。

I don't see any issues at first glance aside from not casting appropriately, try this..

Location loca = (Location)msg.obj;

You can't assign a super class to a subclass without casting, you can however go the other way around.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文