我希望在单击按钮时将当前位置发送到我的firebase数据库中的特定人员。这些人在设备之间进行更改,具体取决于用户选择哪些人来获取有关发件人位置的通知。我知道我需要做什么,但我似乎无法弄明白。
这是我用来阅读用户当前位置的课程: 在我的menuActivity中,我想在单击sendLoc按钮时调用纬度和经度
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
ImageButton fakeCallBtn;
Button sendLoc;
ImageButton notif;
ImageButton flash;
private GoogleMap mMap;
LocationManager locationManager;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
sendLoc=(Button)findViewById(R.id.Locationbtn);
sendLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Location l = gt.getLocation();
if( l == null){
Toast.makeText(getApplicationContext(),"GPS unable to get
Value",Toast.LENGTH_SHORT).show();
}else {
double lat = l.getLatitude();
double lon = l.getLongitude();
Intent lociIntent = new Intent(MenuActivity.this,
ViewLocation.class);
lociIntent.putExtra("lat", lat);
lociIntent.putExtra("lon",lon);
startActivity(lociIntent);
Toast.makeText(getApplicationContext()," Emergency Alert has
been Successfully sent ",Toast.LENGTH_SHORT).show();
}
}
});
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
}
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);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str)); // this is the location i want to share with the specific people in my database
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
@Override
protected void onStop() {
super.onStop();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
@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) {
super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
这是创建一个组的类,当单击按钮发送位置时应该发送该位置:
public class EmergencyList extends AppCompatActivity {
private Toolbar mToolbar;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn, mDeclineBtn;
private DatabaseReference mUsersDatabase;
private ProgressDialog mProgressDialog;
private DatabaseReference mFriendReqDatabase;
private DatabaseReference mFriendDatabase;
private DatabaseReference mNotificationDatabase;
private ImageView mProfileImage;
private DatabaseReference mRootRef;
private FirebaseUser mCurrent_user;
private String mCurrent_state;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_list);
mToolbar = (Toolbar)findViewById(R.id.user_Appbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Who to notify in emergency");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String user_id = getIntent().getStringExtra("user_id");
mRootRef = FirebaseDatabase.getInstance().getReference();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Connection_req");
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contacts");
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notification");
mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mProfileName = (TextView) findViewById(R.id.profile_displayName);
mProfileStatus = (TextView) findViewById(R.id.profile_status);
mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
mDeclineBtn = (Button) findViewById(R.id.profile_decline_btn);
mCurrent_state = "not_emergency_contact";
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading User Data");
mProgressDialog.setMessage("Please wait while we load the user data.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
mUsersDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String display_name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String image = dataSnapshot.child("profile_picture").getValue().toString();
mProfileName.setText(display_name);
mProfileStatus.setText(status);
Picasso.with(EmergencyList.this).load(image).placeholder(R.drawable.my_profile).into(mProfileImage);
if(mCurrent_user.getUid().equals(user_id)){
mDeclineBtn.setEnabled(false);
mDeclineBtn.setVisibility(View.INVISIBLE);
mProfileSendReqBtn.setEnabled(false);
mProfileSendReqBtn.setVisibility(View.INVISIBLE);
}
//--------------- FRIENDS LIST / REQUEST FEATURE -----
mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
String req_type = dataSnapshot.child(user_id).child("emergency_type").getValue().toString();
if(req_type.equals("received")){
mCurrent_state = "emergency_received";
mProfileSendReqBtn.setText("Accept As Emergency ");
mDeclineBtn.setVisibility(View.VISIBLE);
mDeclineBtn.setEnabled(true);
} else if(req_type.equals("sent")) {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Request");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
} else {
mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove "+mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mProfileSendReqBtn.setEnabled(false);
// --------------- NOT FRIENDS STATE ------------
if(mCurrent_state.equals("not_emergency_contact")){
DatabaseReference newNotificationref = mRootRef.child("Emergency_Notification").child(user_id).push();
String newNotificationId = newNotificationref.getKey();
HashMap<String, String> notificationData = new HashMap<>();
notificationData.put("from", mCurrent_user.getUid());
notificationData.put("type", "request");
Map requestMap = new HashMap();
requestMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id + "/emergency_type", "sent");
requestMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid() + "/emergency_type", "received");
requestMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);
mRootRef.updateChildren(requestMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Toast.makeText(EmergencyList.this, "There was some error in sending request", Toast.LENGTH_SHORT).show();
} else {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Contact");
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
// - -------------- CANCEL REQUEST STATE ------------
if(mCurrent_state.equals("emergency_sent")){
mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
});
}
});
}
// ------------ REQ RECEIVED STATE ----------
if(mCurrent_state.equals("emergency_received")){
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id + "/date", currentDate);
friendsMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid() + "/date", currentDate);
friendsMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id, null);
friendsMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove " + mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
}
});
}
// ------------ UNFRIENDS ---------
if(mCurrent_state.equals("emergency_contact")){
Map unfriendMap = new HashMap();
unfriendMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id, null);
unfriendMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(unfriendMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
}
});
}
}
这是我从我的数据库中的Emergency_Contacts呼叫人员的类:
public class EmergencyFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public EmergencyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_emergency, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.emergency_contacts);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
@Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder> emergencyRecyclerViewAdapter = new FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder>(
Emergency.class,
R.layout.users_emergency_layout,
EmergencyFragment.EmergencyViewHolder.class,
mFriendsDatabase
) {
@Override
protected void populateViewHolder(final EmergencyFragment.EmergencyViewHolder emergencyViewHolder, Emergency emergency, int i) {
emergencyViewHolder.setDate(emergency.getDate());
final String user_id = getRef(i).getKey();
mUsersDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String Username = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
emergencyViewHolder.setName(Username);
emergencyViewHolder.setUserImage(userThumb, getContext());
emergencyViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{" Open Details", "view history"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent emergencyIntent = new Intent(getContext(), EmergencyList.class);
emergencyIntent.putExtra("user_id", user_id);
startActivity(emergencyIntent);
}
if(i == 1){
Intent historyIntent = new Intent(getContext(), History.class);
historyIntent.putExtra("user_id", user_id);
historyIntent.putExtra("Username", Username);
startActivity(historyIntent);
}
}
});
builder.show();
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(emergencyRecyclerViewAdapter);
}
public static class EmergencyViewHolder extends RecyclerView.ViewHolder {
View mView;
public EmergencyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.contacts_status);
userStatusView.setText(date);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.contacts_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.image_display);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
}
}
我希望在历史课上存储或打开该位置现在我不知道如何从menuactivity类中获取该位置 - &gt;紧急_联系然后到 - &gt;它将被展示的历史。