如何使用IntentService运行后台服务以将地图坐标插入房间数据库

时间:2019-07-11 07:09:58

标签: android intentservice

我必须每5分钟将用户的位置更新到会议室数据库中,并且它也必须在后台运行。我已经使用LocationRequest和locationCallback来更新位置并将地图坐标存储到房间数据库中。我刚刚读了IntentService,但表现不佳。任何人都可以帮忙做后台服务,还可以根据我的代码检查我是否已经正确完成了操作。

MapsActivity.java:

     public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    private GoogleMap mMap;
    private FusedLocationProviderClient fusedLocationClient;
    private static final int LOCATION_REQUEST_CODE = 101;

    private Location currentLocation;
    private LocationRequest mLocationRequest;
    private Marker mLocationMarker;
    private static final int Request_UserLocation = 99;
    public LocationDatabase mRoomDatabase;
    protected ResultReceiver receiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mRoomDatabase = Room.databaseBuilder(getApplicationContext(), LocationDatabase.class, "locationdb").allowMainThreadQueries().build();

        fetchLastLocation();

    }

    private void fetchLastLocation() {

        if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
            return;
        }
        Task<Location> task = fusedLocationClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    currentLocation = location;
                    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.map);

                    mapFragment.getMapAsync(MapsActivity.this);
                } else {
                    Toast.makeText(getApplicationContext(), "No Location recorded", Toast.LENGTH_LONG).show();
                }
            }
        });

    }

   @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);

        mLocationRequest=new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(10000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                fusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                mMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            fusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mMap.setMyLocationEnabled(true);
        }
    }

   LocationCallback mLocationCallback=new LocationCallback() {
        @Override
       public void onLocationResult(LocationResult locationResult){
            List<Location> locationList=locationResult.getLocations();
            if(locationList.size() > 0){
                Location location=locationList.get(locationList.size() - 1);
                Log.d("MapsActivity","Location:" +location.getLatitude()+","+location.getLongitude());
                currentLocation=location;
                if(mLocationMarker != null){
                    mLocationMarker.remove();
                }
                LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
                MarkerOptions markerOptions=new MarkerOptions().position(latLng).title("You are here");
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15f));
                mMap.addMarker(markerOptions);

                LocationsModel mLocate=new LocationsModel();
                mLocate.setLatitude(location.getLatitude());
                mLocate.setLongitude(location.getLongitude());
                mRoomDatabase.mLocateDao().addLocations(mLocate);
                Toast.makeText(getApplicationContext(), "Location added successfully", Toast.LENGTH_LONG).show();


            }
        }

    };



    private void checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

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

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        Request_UserLocation );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        Request_UserLocation );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResult) {
        switch (requestCode) {
            case LOCATION_REQUEST_CODE:
                if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                    fetchLastLocation();
                } else {
                    Toast.makeText(MapsActivity.this,"Permission Denied",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        if(mLocationMarker != null){
            mLocationMarker.remove();

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(fusedLocationClient != null){
            fusedLocationClient.removeLocationUpdates(mLocationCallback);
        }
    }
}

0 个答案:

没有答案