我试图将车手的请求发送给像超人一样的司机。我使用的是Firebase云消息传递 我的代码没有任何错误,但我似乎无法发送请求。
我在youtube上有这个教程,请查看我的代码,让我知道我在做什么不同。
DriverActivity.class
public class DriverActivity 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 static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL =3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
ImageView ivPin;
private List<LatLng> polyLineList;
private Marker carMarker;
private float v;
private double lat,lng;
private Handler handler;
private LatLng startPosition, endPosition, currentPosition;
private int index,next;
private PlaceAutocompleteFragment Places;
private String destination;
private PolylineOptions polylineOptions, blackPolylineOptions;
private Polyline blackPolyline, greyPolyline;
private IGoogleAPI mService;
Runnable drawPathRunnable = new Runnable() {
@Override
public void run() {
if (index<polyLineList.size()-1){
index++;
next = index+1;
}
if (index <polyLineList.size()-1){
startPosition = polyLineList.get(index);
endPosition = polyLineList.get(next);
}
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,1);
valueAnimator.setDuration(3000);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
v = valueAnimator.getAnimatedFraction();
lng = v*endPosition.longitude+(1-v)*startPosition.longitude;
lat = v*endPosition.latitude+(1-v)*startPosition.latitude;
LatLng newPos = new LatLng(lat,lng);
carMarker.setPosition(newPos);
carMarker.setAnchor(0.5f,0.5f);
carMarker.setRotation(getBearing(startPosition,newPos));
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(newPos)
.zoom(15.5f)
.build()));
}
});
valueAnimator.start();
handler.postDelayed(this,3000);
}
};
private float getBearing(LatLng startPosition, LatLng endPosition) {
double lat = Math.abs(startPosition.latitude - endPosition.latitude);
double lng = Math.abs(startPosition.longitude - endPosition.longitude);
if (startPosition.latitude < endPosition.latitude && startPosition.longitude <endPosition.longitude)
return (float)(Math.toDegrees(Math.atan(lng/lat)));
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude )
return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+90);
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float)(Math.toDegrees(Math.atan(lng/lat))+180);
else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude )
return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+270);
return -1;
}
//Car animation
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_main);
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();
mMap.clear();
handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT)
.show();
}
}
});
polyLineList = new ArrayList<>();
ivPin = (ImageView)findViewById(R.id.ivPin);
Places = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
Places.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
if (location_switch.isChecked()){
destination = place.getAddress().toString();
destination = destination.replace(" ", "+");
getDirection();
}
else
{
Toast.makeText(DriverActivity.this, "Please change your status to ONLINE", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Status status) {
Toast.makeText(DriverActivity.this, ""+ status.toString(), Toast.LENGTH_SHORT).show();
}
});
//geo fire
drivers = FirebaseDatabase.getInstance().getReference(Common.tow_driver_location_tbl);
geoFire = new GeoFire(drivers);
setUpLocation();
mService = Common.getGoogleAPI();
updateFirebaseToken();
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(DriverActivity.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(DriverActivity.this, TripBill.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
payments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openNotifications = new Intent(DriverActivity.this, EarningsFragment.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
notifications.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openNotifications = new Intent(DriverActivity.this, NotificationsFragment.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openHelp = new Intent(DriverActivity.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(DriverActivity.this, About.class);
startActivity(openAbout);
drawer.closeDrawer(GravityCompat.START);
}
});
}
private void updateFirebaseToken() {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tbl);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(token);
}
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude());
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"+
"transit_routing_preference=less_driving&"+
"origin=" +currentPosition.latitude+ "," + currentPosition.longitude + "&" +
"destination="+ destination +"&"+
"keys="+ getResources().getString(R.string.google_direction_api);
Log.d("EDMTDEV", requestApi); //Print URL for debug
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i<jsonArray.length();i++)
{
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
//Adjusting bounds
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng:polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 2);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolylineOptions.addAll(polyLineList);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size()-1))
.title("Pickup Location"));
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0,100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int)valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue/100.0f));
List<LatLng> p = points.subList(0,newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.towin)));
handler = new Handler();
index=-1;
next=1;
handler.postDelayed(drawPathRunnable,3000);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
//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, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED )
{
//Request runtime permissions
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.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(FASTEST_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 (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){
return;
}
Common.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (Common.mLastLocation != null){
if (location_switch.isChecked()){
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.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()
.position(new LatLng(latitude, longitude))
.title("Your Location"));
//move camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15.0f));
//Draw animation rotate marker
}
});
}
}
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, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.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;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onLocationChanged(Location location) {
Common.mLastLocation = location;
displayLocation();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
我不知道为什么我无法发送发送通知