首页 > 解决方案 > 广播数据未通过

问题描述

我正在尝试制作一个使用服务跟踪设备位置并在谷歌地图上显示该位置的应用程序。但是我觉得服务中的代码根本没有执行。当我尝试检索纬度和经度并将其分配给 LatLng 对象时,我不能,因为它们为空。

以下是主要活动:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final String TAG = "MapActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1000;
    private static final int ERROR_DIALOG_REQUEST = 1001;
    private static final float DEFAULT_ZOOM = 15f;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private BroadcastReceiver mBroadcastReceiver;
    private LatLng currentLocation;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (isServicesOK()) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
        }
        getLocationPermission();
        startMyService();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: resumed from service");
        if (mBroadcastReceiver == null) {
            Log.d(TAG, "onResume: broadcastReceiver == null");
            mBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Log.d(TAG, "onReceive: receiving current location");
                    currentLocation = new LatLng((double) intent.getExtras().get("latitude"),
                            (double) intent.getExtras().get("longitude"));
                }
            };
        }
        Log.d(TAG, "onResume:"+ currentLocation.toString());
        registerReceiver(mBroadcastReceiver, new IntentFilter("location"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this.getApplicationContext(), MyService.class);
        stopService(intent);
        if(mBroadcastReceiver != null){
            unregisterReceiver(mBroadcastReceiver);
        }

    }

    private void startMyService() {
        Log.d(TAG, "startMyService: starting to track devices location");
        Intent intent = new Intent(this.getApplicationContext(), MyService.class);
        startService(intent);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;
        if (currentLocation != null) {
            moveCamera(currentLocation, 15f);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // auto-generated permission check
                return;
            }
            mMap.setMyLocationEnabled(true);
        }
    }

    private void moveCamera(LatLng latLng, float zoom){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapsActivity.this);
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch(requestCode){
            case LOCATION_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

    public boolean isServicesOK(){
        Log.d(TAG, "isServicesOK: checking google services version");
        int availvable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MapsActivity.this);

        if(availvable == ConnectionResult.SUCCESS){
            //everything is fine
            Log.d(TAG, "isServicesOK: google play services is working");
            return true;
        }

        else if(GoogleApiAvailability.getInstance().isUserResolvableError(availvable)) {
            //an error occured but we can resolve it
            Log.d(TAG, "isServicesOK: an error occured but we can fix it");
            Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MapsActivity.this,availvable, ERROR_DIALOG_REQUEST); dialog.show();
        }else{
            Toast.makeText(this,"You can't make map request", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
}

服务等级:

public class MyService extends Service {

    private LocationListener listener;
    private LocationManager locationManager;
    private static final String TAG = "MyService";
    private FusedLocationProviderClient mFusedLocationProviderClient;

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

    @SuppressLint("MissingPermission")
    @Override
    public void onCreate() {
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            final Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if(task.isSuccessful()){
                        Log.d(TAG, "onComplete: found location!");
                        Location currentLocation = (Location) task.getResult();
                        Intent intent = new Intent("location");
                        intent.putExtra("latitude", currentLocation.getLatitude());
                        intent.putExtra("longitude", currentLocation.getLongitude());
                        sendBroadcast(intent);
                    }else{
                        Log.d(TAG, "onComplete: current location is null");
                    }
                }
            });

        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }
}

我知道如何获取当前位置并更新地图,但不使用服务。但我需要这样做——通过服务。而且我不知道我的错误在哪里。

标签: javaandroidservicebroadcastreceiver

解决方案


推荐阅读