-2

我想从中获取location并将background其提交给serverso ,这是执行相同操作的最佳选择Job scheduleror Service。为什么?我也想知道job scheduler我们连续web api打电话时节省的电池。

4

2 回答 2

0

如果您将“最佳选择”定义为“最省电的方式”:尽量减少主动连接互联网以读取或传输数据的呼叫。

而是实现一个广播接收器,告诉您的应用程序已经有互联网流量。当您的应用收到广播通知时,它可以添加自己的互联网流量。这样,您的应用程序可以避免连接到互联网的电池开销,这是非常昂贵的电池。

有关详细信息,请参阅https://developer.android.com/training/efficient-downloads/efficient-network-access.html上的“捆绑转移”

于 2017-04-18T13:45:58.610 回答
0

这是我的实现,我不使用Job Scheduler或者Service因为没有必要。我使用Application该类,因此您将能够在您的所有应用程序中获取用户的位置。

首先,您需要创建一个LocationHelper类,它将为您完成所有工作:

public class LocationHelper implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final int REQUEST_LOCATION_PERMISSION = 0;
    private static final int REQUEST_RESOLVE_ERROR = 1;

    private static GoogleApiClient mGoogleApiClient;
    private Fragment mFragment;
    private final Activity mActivity;
    private final Callback mCallback;

    private Location mLastLocation;
    private boolean mResolvingError;
    private LocationRequest mLocationRequest;
    private boolean mRegisterLocationUpdates;

    public interface Callback {
        void onLastLocation(Location userLocation);
    }

    public LocationHelper(Fragment fragment, Callback callback) {
        this(fragment.getActivity(), callback);
        mFragment = fragment;
    }

    public LocationHelper(Activity activity, Callback callback) {
        mActivity = activity;
        mCallback = callback;

        mLocationRequest = new LocationRequest();

        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        obtainLastLocation();
    }

    private void obtainLastLocation() {

        // Verifies if user give us permission to obtain its suggestionLocationV2.
        if (ActivityCompat.checkSelfPermission(mActivity,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mActivity,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
                    Manifest.permission.ACCESS_COARSE_LOCATION)) {

                // Show an explanation to the user why we need its suggestionLocationV2.
                requestPermissionRationale();

            } else {

                requestPermission();
            }

            // We don't have user permission to get its geo suggestionLocationV2, abort mission.
            return;
        }

        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
            return;
        }

        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (lastLocation != null) {
            onLocationChanged(lastLocation);
        } else {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            mRegisterLocationUpdates = true;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location == null) return;

        removeLocationUpdatesIfNeed();

        mLastLocation = location;
        DirectoryApp.getInstance().setLastLocation(mLastLocation);

        if (mCallback != null) {
            mCallback.onLastLocation(mLastLocation);
        }
    }

    private void removeLocationUpdatesIfNeed() {
        if (mRegisterLocationUpdates && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mRegisterLocationUpdates = false;
        }
    }

    private void requestPermission() {
        // Lets ask suggestionLocationV2 permission to user.
        if (mFragment != null) {
            mFragment.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        } else {
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    private void requestPermissionRationale() {
        new AlertDialog.Builder(mActivity)
                .setMessage("We need the suggestionLocationV2 to provide you best results.")
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermission();
                    }
                })
                .show();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result) {

        // If not already attempting to resolve an error.
        if (!mResolvingError) {

            if (result.hasResolution()) {

                try {
                    mResolvingError = true;
                    result.startResolutionForResult(mActivity, REQUEST_RESOLVE_ERROR);
                } catch (IntentSender.SendIntentException e) {
                    // There was an error with the resolution intent. Try again.
                    mGoogleApiClient.connect();
                }

            } else {
                GooglePlayServicesUtil.showErrorDialogFragment(result.getErrorCode(), mActivity,
                        null, REQUEST_RESOLVE_ERROR, null);
                mResolvingError = true;
            }
        }
    }


    // The follow methods should be called in Activity or Fragment.
    public void onStart() {
        mGoogleApiClient.connect();
    }

    public void onStop() {
        removeLocationUpdatesIfNeed();
        mGoogleApiClient.disconnect();
    }

    public void onRequestPermissionResult(int requestCode, String[] permissions,
                                          int[] grantResults) {
        if (requestCode == REQUEST_LOCATION_PERMISSION
                && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // Permission granted. Uhull lets get its suggestionLocationV2 now.
            obtainLastLocation();
        }
    }
}

请注意,当位置更改时,我们调用 Application 类来设置新位置,因此在您的 Application 类中您必须创建方法:

public class Application extends MultiDexApplication {

    private static App instance;

    private Location mLastLocation;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
   }

    public void setLastLocation(Location lastLocation) {
        mLastLocation = lastLocation;
    }

    public Location getLastLocation() {
        return mLastLocation;
   }

最后,当您必须使用位置时,在Fragment或上Activity,只需使用正确的方法启动和停止它。

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationHelper = new LocationHelper(this, this);
    }

    @Override
    public void onStart() {
        super.onStart();
        locationHelper.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        locationHelper.onStop();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        locationHelper.onRequestPermissionResult(requestCode, permissions, grantResults);
    }
于 2017-04-18T13:10:04.613 回答