简体   繁体   English

将 Object 从 Activity 传递到 Service,Object 无法实现 Serializable 或 Parcable

[英]Pass an Object from Activity to Service, the Object can't implement Serializable or Parcable

I have an assignment for Android Development in Java, with the Google Maps api.我在 Java 有一个 Android 开发的任务,谷歌地图 api。

I have the Maps Activity and a separate location service that tracks the device's location, and i want to add a google maps tracker when the location of the device changes.我有地图活动和跟踪设备位置的单独位置服务,我想在设备位置更改时添加谷歌地图跟踪器。 I can do that if i pass the GoogleMap mMap object into the locationListener class i created:如果我将 GoogleMap mMap object 传递到我创建的 locationListener class 中,我可以做到这一点:


public class LocationListener implements android.location.LocationListener
{
    private Location        cur_location;
    private LocationManager locationManager;
    private GoogleMap       mMap;
    
    @SuppressLint("MissingPermission")
    public LocationListener(LocationManager locationManager , GoogleMap mMap)
    {
        this.locationManager = locationManager;
        this.mMap            = mMap;
        this.cur_location    = getLastKnownLocation();
        
    }
    
    @SuppressLint("MissingPermission")
    private Location getLastKnownLocation() {
        List<String> providers = locationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = locationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        return bestLocation;
    }
    
    @Override
    public void onLocationChanged(@NonNull Location location)
    {
        Log.e("LocationListener" , location.toString());
        cur_location = location;
        mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude() , location.getLongitude())).title("Marker"));
    }
    
    public Location getCur_location()
    {
        return cur_location;
    }
    
}

problem is that the LocationListener is initialised in the Service but the Location from the function getCur_location() needs to be accessed in the Activity therefore i need to pass the GoogleMap mMap object from the Activity to the Service.问题是 LocationListener 是在服务中初始化的,但是需要在活动中访问来自 function getCur_location()的位置,因此我需要将 GoogleMap mMap object 从活动传递到服务。

The only way i know how to do that is through the Intent Extras, but the GoogleMap class doesn't implement Serializable nor Parcable.我知道如何做到这一点的唯一方法是通过 Intent Extras,但 GoogleMap class 没有实现 Serializable 或 Parcable。

Is there another way to pass an Object from an Activity to a Service?还有另一种方法可以将 Object 从活动传递到服务吗?

I am assuming that the LocationListener is used within a Service class which you do not include in your question.我假设 LocationListener 在 Service class 中使用,您不包含在您的问题中。 You can achieve passing an object to the service if the service is a bound service.如果服务是绑定服务,您可以将 object 传递给服务。 Check this documentation检查此 文档

Before proceeding explaining how, I want to note that something sounds wrong in this and needs deeper thought on how else you could avoid it在继续解释方法之前,我想指出这听起来有些不对劲,需要更深入地思考如何避免它

Within your service create a variable to hold the map object and then create an inner class extending the Binder and create an object of it like below在您的服务中创建一个变量来保存 map object 然后创建一个内部 class 扩展Binder并创建一个 object 如下所示

    private GoogleMap mMap = null;
    private LocalBinder mBinder = new LocalBinder();
    public class LocalBinder extends Binder {
        public void setMap(GoogleMap map) {
            mMap = map;
        }
    }

Then make sure you clear the mMap when the service is not bound anymore然后确保在服务不再绑定时清除 mMap

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mMap = null;
        return true;
    }

Now all you have to do is in your activity create a serviceConnection and bind to the service.现在您所要做的就是在您的活动中创建一个 serviceConnection 并绑定到该服务。

   private MyService.LocalBinder mServiceBinder = null;

   private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceBinder = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mServiceBinder = (MyService.LocalBinder) service);
            // Now you can use the mServiceBinder to call setMap to pass your object to the service
        }
    };

You can bind anywhere you need (eg inside your onCreate) using the following code您可以使用以下代码绑定到您需要的任何位置(例如在您的 onCreate 中)

Intent intent = new Intent(this, MyService.class);
boolean bound = getApplicationContext().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM