尝试添加com.google.anddroid.gms.location.locationRequest后,我的应用不断崩溃

时间:2018-04-03 07:53:48

标签: android

我在尝试解决requestLocationUpdates时遇到错误,好的,我已经按照各种教程进行了操作但仍然遇到了同样的错误,我的应用程序一直在崩溃。我已经准备好实现了android.location.Locationlistener,并且还使用了com.google.android.gms.location.locationRequest

任何人都可以帮我解决这个问题。

  

17263 / com.hushtagstudios.mac.towmedelivery E / UncaughtException:java.lang.ClassCastException:com.hushtagstudios.mac.towmedelivery.DrawerActivity无法强制转换为com.google.android.gms.location.LocationListener                                                                                                at com.hushtagstudios.mac.towmedelivery.DrawerActivity.startLocationUpdates(DrawerActivity.java:416)                                                                                                在com.hushtagstudios.mac.towmedelivery.DrawerActivity.onConnected(DrawerActivity.java:508)

package com.hushtagstudios.mac.towmedelivery;

import android.Manifest; 
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import     
com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class DrawerActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener, 
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{

public static GoogleMap mMap;

//play services res
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICES_RES_REQUEST = 7001;

private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location  mLastLocation;

private static int UPDATE_INTERVAL = 5000;
private static int FATEST_INTERVAL =3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;


Marker mCurrent;
MaterialAnimatedSwitch location_switch;

SupportMapFragment mapFragment;


TableRow myAccount, history, payments, notifications, invite, help, about, 
driveWithTowMe;
TextView name, email;
ImageView profilePicture;

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



    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);

    location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
    location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean IsOnline) {
            if (IsOnline){
                startLocationUpdates();
                displayLocation();
                Snackbar.make(mapFragment.getView(),"You are online", Snackbar.LENGTH_SHORT)
                        .show();

            }else {
                stopLocationUpdates();
                mCurrent.remove();
                Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT)
                        .show();
            }

        }
    });

    //geo fire

    drivers = FirebaseDatabase.getInstance().getReference("DeliveryDatabase");
    geoFire = new GeoFire(drivers);

    setUpLocation();





    final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    name = (TextView) findViewById(R.id.name);
    email = (TextView) findViewById(R.id.email);
    profilePicture = (ImageView) findViewById(R.id.profilePicture);

    myAccount = (TableRow) findViewById(R.id.myAccount);
    history = (TableRow) findViewById(R.id.history);
    payments = (TableRow) findViewById(R.id.myPayments);
    notifications = (TableRow) findViewById(R.id.notifications);
    help = (TableRow) findViewById(R.id.help);
    about = (TableRow) findViewById(R.id.about);
    driveWithTowMe = (TableRow) findViewById(R.id.DriveWithTowMe);

    myAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openMyAccount =  new Intent(DrawerActivity.this, Dashboard.class);
            startActivity(openMyAccount);
            drawer.closeDrawer(GravityCompat.START);
                      finish();
               }
       });

    history.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openNotifications = new Intent(DrawerActivity.this, TripBill.class);
            startActivity(openNotifications);
            drawer.closeDrawer(GravityCompat.START);
        }
    });

    payments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openNotifications = new Intent(DrawerActivity.this, EarningsFragment.class);
            startActivity(openNotifications);
            drawer.closeDrawer(GravityCompat.START);
        }
    });

    notifications.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openNotifications = new Intent(DrawerActivity.this, NotificationsFragment.class);
            startActivity(openNotifications);
            drawer.closeDrawer(GravityCompat.START);
        }
    });


    help.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openHelp = new Intent(DrawerActivity.this, HelpActivity.class);
            startActivity(openHelp);
            drawer.closeDrawer(GravityCompat.START);
        }
    });
    driveWithTowMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            drawer.closeDrawer(GravityCompat.START);
        }
    });


    about.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent openAbout = new Intent(DrawerActivity.this, About.class);
            startActivity(openAbout);
            drawer.closeDrawer(GravityCompat.START);
        }
    });




}

//Press Ctrl+O
//Because we request runtime permission, we need override OnRequestPermissionResult method


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){

        case MY_PERMISSION_REQUEST_CODE:

            if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                if (checkPlayServices()){

                    buildGoogleApiClient();
                    createLocationRequest();

                    if (location_switch.isChecked()){

                        displayLocation();
                    }
                }
            }
    }
}

private void setUpLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED  )
    {
        //Request runtime permissions

       ActivityCompat.requestPermissions(this, new String[]{
               Manifest.permission.ACCESS_COARSE_LOCATION,
               Manifest.permission.ACCESS_FINE_LOCATION
       },MY_PERMISSION_REQUEST_CODE);

    } else {

        if (checkPlayServices()){

            buildGoogleApiClient();
            createLocationRequest();

            if (location_switch.isChecked()){

                displayLocation();
            }
        }

    }





}

private void createLocationRequest() {


    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FATEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);




}

private void buildGoogleApiClient() {

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

    mGoogleApiClient.connect();
}

private boolean checkPlayServices() {

    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS){

        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RES_REQUEST).show();

            else {
            Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
            finish();

            }
            return false;
    }
    return true;
}

private void stopLocationUpdates() {

    if (android.support.v4.app.ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
            android.support.v4.app.ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED  ){
        return;
    }

    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}


private void displayLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED  ){
        return;
    }

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLastLocation != null){

        if (location_switch.isChecked()){
            final double latitude = mLastLocation.getLatitude();
            final double longitude = mLastLocation.getLongitude();

            //update to firebase

            geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {

                    //Add Marker

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

                        mCurrent = mMap.addMarker(new MarkerOptions()
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_towtruck))
                        .position(new LatLng(latitude,longitude))
                        .title("You"));
                    }

                    //move camera to this position

                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));

                    //Draw animation rotate marker
                    rotateMarker(mCurrent,-360, mMap);

                }
            });
        }
    }
    else {

        Log.d("ERROR", "Cannot get your location");

    }


}

private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {

    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final float startRotation = mCurrent.getRotation();
    final long duration = 1500;

    final LinearInterpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {

            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float)elapsed/duration);
            float rot = t * i + (1 - t ) * startRotation;
            mCurrent.setRotation(-rot > 180?rot/2:rot);

            if (t<1.0){

                handler.postDelayed(this,16);
            }
        }
    });
}

private void startLocationUpdates() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED  ){

        return;
    }

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

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.drawer, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
}

@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    displayLocation();

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onConnected(@Nullable Bundle bundle) {
    displayLocation();
    startLocationUpdates();

}

@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();

}

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

}
}

1 个答案:

答案 0 :(得分:0)

我不知道为什么你使用了两个不同的LocationListener

无论如何,您在班级中实施的LocationListenerandroid.location.LocationListener,但您需要com.google.android.gms.location.LocationListener

在第416行中,当您要求进行位置更新LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);

时,您将当前的LocationListener作为第三个参数传递

所以它崩溃了。

只需尝试导入com.google.android.gms.location.LocationListener而不是android.location.LocationListener并检查。