如何将数据从Android后台服务传递到活动

问题描述 投票:1回答:2

我有一个具有两个组件的Android应用

  1. 创建,显示并与在Webview中运行的javascript代码进行通信的活动。
  2. 一个创建并绑定到上述活动的后台服务,即使用户看不到该活动,该服务也会捕获位置数据。

[有人可以告诉我将位置数据从服务传递回活动的最简单方法,无论活动是否显示给用户,该活动都将起作用。

我应该使用EventBus吗?广播接收器,本地广播管理器还是什么?

理想情况下,我想指出一个在GitHub(或类似版本)上的示例应用程序的方向,我可以下载它的工作方式以检查其工作方式,否则某些代码会很好。

android background-service
2个回答
1
投票

这是您的服务:

<service
    android:name=".Services.Service.GPSTracker"
    android:exported="false" />

和java类:

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import static android.location.GpsStatus.GPS_EVENT_SATELLITE_STATUS;

public class GPSTracker extends Service {

    private Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    float bearing; // bearing

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000; // 5 sec

    // Declaring a Location Manager
    protected LocationManager locationManager;
    protected LocationListener locationListenerNetwork;
    protected LocationListener locationListenerGPS;
    protected GpsStatus.Listener gpsStatusListener;
    protected GpsListener gpsListener;


    public GPSTracker(Context context, LocationListener listenerNetwork, LocationListener listenerGPS, GpsListener gpsListener) {
        locationListenerGPS = listenerGPS;
        locationListenerNetwork = listenerNetwork;
        this.mContext = context;
        this.gpsListener = gpsListener;
        getLocation();
    }

    public GPSTracker() {
    }

    private GPSTracker(Context mContext) {
        this.mContext = mContext;
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return null;
                        }


                        final Criteria criteria = new Criteria();
                        criteria.setCostAllowed(true);
                        criteria.setPowerRequirement(Criteria.POWER_HIGH);
                        criteria.setAccuracy(Criteria.ACCURACY_FINE);
                        final String p = locationManager.getBestProvider(criteria, true);

                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerGPS);
                        gpsStatusListener = new GpsStatus.Listener() {
                            @Override
                            public void onGpsStatusChanged(int event) {
                                if (event == GPS_EVENT_SATELLITE_STATUS) {
                                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                        // TODO: Consider calling
                                        //    ActivityCompat#requestPermissions
                                        // here to request the missing permissions, and then overriding
                                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                        //                                          int[] grantResults)
                                        // to handle the case where the user grants the permission. See the documentation
                                        // for ActivityCompat#requestPermissions for more details.
                                        return;
                                    }
                                    GpsStatus status = locationManager.getGpsStatus(null);
                                    Iterable<GpsSatellite> sats = status.getSatellites();
                                    gpsListener.OnGpsSatelliteChanged(sats);
                                    // Check number of satellites in list to determine fix state
                                }
                            }
                        };
                        locationManager.addGpsStatusListener(gpsStatusListener);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                bearing = location.getBearing();
                            }
                        }
                    }
                }
                if (isNetworkEnabled) {
                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return null;
                    }
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerNetwork);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            bearing = location.getBearing();
                        }
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPSProvider() {
        if (locationManager != null) {
            locationManager.removeUpdates(locationListenerGPS);
        }
    }

    public void stopUsingNetworkProvider() {
        if (locationManager != null) {
            locationManager.removeUpdates(locationListenerNetwork);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    public float getBearing() {
        if (location != null) {
            bearing = location.getBearing();
        }
        return bearing;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
       /*
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {*/
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
          /*  }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();*/
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public interface GpsListener {
        void OnGpsSatelliteChanged(Iterable<GpsSatellite> gpsSatellites);
    }

}

活动中:

 GPSTracker gps;


    LocationListener locationListenerNetwork = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    LocationListener locationListenerGPS = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {


        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

     GPSTracker.GpsListener gpsListener = new GPSTracker.GpsListener() {
        @Override
        public void OnGpsSatelliteChanged(Iterable<GpsSatellite> gpsSatellites) {

        }
    };


    void start(){
        gps = new GPSTracker(this, locationListenerNetwork, locationListenerGPS, gpsListener);
    }

    void stop(){
        if (gps != null) {
            gps.stopUsingGPSProvider();
            gps.stopUsingNetworkProvider();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        stop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        start();
    }

以上代码将在您的活动打开时运行gps,并开始向您的活动发送gps数据,并且如果活动进入后台或停止等等。gps也将停止(您也需要处理权限)。同样,如果即使在活动未打开的情况下也要获取gps数据,则可以制作一个List<location>并将其保存在服务中,并在重置活动后通过接口将其发送回(希望您知道如何创建接口并传递数据) );


0
投票

由于使用的是Bound service,最简单的方法是当Binder绑定到Activity时返回适当的Service对象。

该文档在here中。

而且,这是绑定的service和对应的actvitiy的示例代码。

请注意,Activity一旦建立连接,便能够调用添加到相应Binder对象的公共方法。如果您希望Service自行决定向Activity提供信息,则只需注册该服务可以调用的侦听器。

© www.soinside.com 2019 - 2024. All rights reserved.