从Service into Activity获取值

时间:2017-01-24 16:56:51

标签: java android service

我使用fusedapi编写下面的代码来获取lat和longi。

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * Created by DELL WORLD on 1/24/2017.
 */

public class LocationWithFusedApi extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private LocationRequest mLocationRequest;
    double lat, lon;
     final static String Mydata = "MyData";

  /*  public LocationWithFusedApi() {
        super("LocationWithFusedApi");
    }*/
/*
    @Override
    public void onDestroy() {
        super.onDestroy();
        mGoogleApiClient.disconnect();
    }*/

    @Override
    public void onStart(Intent intent, int startId) {
        Log.d("LocationWithFusedAPI", "Called");
        super.onStart(intent, startId);
        mGoogleApiClient.connect();
    }

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

   /* @Override
    protected void onHandleIntent(Intent intent) {

    }*/

    @Override
    public void onCreate() {
        super.onCreate();
        buildGoogleApiClient();
    }

    @Override
    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lon = location.getLongitude();
        System.out.println("Latest" + lat + ":" + lon);
        Intent intent = new Intent();
        intent.setAction("Mydata");
        intent.putExtra("lat",lat);
        intent.putExtra("lon",lon);
        sendBroadcast(intent);
        sendlat();
        sendlon();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(100); // Update location every second

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = mLastLocation.getLatitude();
            lon = mLastLocation.getLongitude();
            System.out.println("Last" + lat + ":" + lon);
            sendlat();
            sendlon();

        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }

    synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    public double sendlat() {
        return lat;
    }

    public double sendlon() {
        return lon;
    }

    public void removeupdate() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}

现在尝试在另一个活动中获取lat和lon值,以通过调用sendlat和sendlon向用户显示但是获取null。我在做什么错。 这是我试图获取值的活动代码。

  public class ShareLocation extends AppCompatActivity {
    GPSDataPicker gps;
    String clickable = "";
    Latlonreceiver latlonreceiver;
    double lat, lon;

    @Override
    protected void onStart() {
        latlonreceiver = new Latlonreceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationWithFusedApi.Mydata);
        registerReceiver(latlonreceiver, intentFilter);

        Intent intent = new Intent(ShareLocation.this, LocationWithFusedApi.class);
        startService(intent);
        super.onStart();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       /* LocationWithFusedApi locationWithFusedApi = new LocationWithFusedApi();
        double latitude = locationWithFusedApi.sendlat();
        double longitude = locationWithFusedApi.sendlon();*/

        double latitude = lat;
        double longitude = lon;
        setContentView(R.layout.sharelocation);



                        clickable = "https://maps.google.com/?q=" + latitude + "," + longitude;
}
}
 @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(latlonreceiver);
    }
  public class Latlonreceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            lat = intent.getDoubleExtra("lat", 0.0);
            lon = intent.getDoubleExtra("lon", 0.0);

        }
    }

1 个答案:

答案 0 :(得分:0)

研究使用广播接收器。这里的基本错误是位置的检索异步地在不同的线程上运行。因此,当您调用sendXxx()方法时,该位置尚未解析。使用异步代码,您需要服务在解析位置后将结果推送给您。这种情况下的标准方式是广播接收器。