开发者

Passing Location object from a Service to a handler in the Activity

开发者 https://www.devze.com 2023-02-20 10:20 出处:网络
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 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 开发者_StackOverflow社区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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消