当我的用户登录或注销时会出现问题(所有这一切都是将我的数据库中名为“logged_in”的每个用户下的子项更改为true或false)。当他们这样做时,它会向其他用户的手机发送大量新通知,我不知道为什么会这样。我怎样才能让firebase只发送一次通知然后忘掉它?为什么它甚至通过通知存储/记忆?
这是我部署的云功能。
function Efar (distance_away, token, message) {
this.distance_away = distance_away;
this.token = token;
this.message = message;
this.getToken = function() {
return this.token;
}
this.getMessage = function() {
return this.message;
}
}
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotificationAdded = functions.database.ref('/emergencies/{id}').onCreate(event => {
return admin.database().ref('/tokens').on('value', function(snapshot) {
var efarArray = snapshotToArray(snapshot, event.data.child('latitude').val(), event.data.child('longitude').val());
efarArray.sort(function(a, b) {
return a.distance - b.distance;
});
var payload = {
notification: {
title: "New stuff :)",
body: "Info given: " + event.data.child('other_info').val(),
//badge: '1',
sound: 'default',
}
};
tokens_to_send_to = [];
if(efarArray.length >= 5){
//only send to the 5 closest efars
for (var i = 4; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}else{
for (var i = efarArray.length - 1; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}
return admin.messaging().sendToDevice(tokens_to_send_to, payload).then(response => {
});
});
});
//code for function below from https://ilikekillnerds.com/2017/05/convert-firebase-database-snapshotcollection-array-javascript/
function snapshotToArray(snapshot, incoming_latitude, incoming_longitude) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var distance_to_efar = distance(childSnapshot.child('latitude').val(), childSnapshot.child('longitude').val(), incoming_latitude, incoming_longitude);
var item = {
latitude: childSnapshot.child('latitude').val(),
longitude: childSnapshot.child('longitude').val(),
token: childSnapshot.key,
distance: distance_to_efar
};
returnArr.push(item);
});
return returnArr;
};
这是我的android登录类:
public class loginScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
//button to get back to patient screen
Button backButton = (Button) findViewById(R.id.login_back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launchPatientScreen();
finish();
}
});
Button submitButton = (Button) findViewById(R.id.login_submit_button);
final EditText user_name = (EditText) findViewById(R.id.login_name_field);
final EditText user_id = (EditText) findViewById(R.id.login_id_field);
final TextView errorText = (TextView) findViewById(R.id.errorLoginText);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String old_id = sharedPreferences.getString("old_id", "");
String old_name = sharedPreferences.getString("old_name", "");
if(old_id != "" && old_name != ""){
user_name.setText(old_name);
user_id.setText(old_id);
}
// logic for the login submit button
submitButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final String name = user_name.getText().toString();
final String id = user_id.getText().toString();
// make sure there is some data so app doesn't crash
if (name.equals("") || id.equals("")) {
Log.wtf("Login", "No data input. Cannot attempt login");
errorText.setText("ERROR: missing username or id...");
} else {
// check and validate the user
checkUser(name, id);
}
}
}
);
}
// Starts up launchEfarScreen screen
private void launchEfarScreen() {
Intent toEfarScreen = new Intent(this, EFARMainActivity.class);
finish();
startActivity(toEfarScreen);
}
// Starts up launchEfarScreen screen
private void launchPatientScreen() {
Intent toPatientScreen = new Intent(this, PatientMainActivity.class);
startActivity(toPatientScreen);
finish();
}
// checks to see if a user exists in the database
private void checkUser(String user_name, String user_id) {
final TextView errorText = (TextView) findViewById(R.id.errorLoginText);
final String name = user_name;
final String id = user_id;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users");
userRef.addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void onDataChange (DataSnapshot snapshot){
// Check if id number is in database
if (snapshot.hasChild(id)) {
// check if name matches id in database
String check_name = snapshot.child(id + "/name").getValue().toString();
if (check_name.equals(name)) {
// store password and username for auto login
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("id", id);
editor.putString("name", name);
editor.putString("old_id", id);
editor.putString("old_name", name);
editor.putBoolean("logged_in", true);
editor.commit();
// update users info
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users");
GPSTracker gps = new GPSTracker(loginScreen.this);
double my_lat = gps.getLatitude(); // latitude
double my_long = gps.getLongitude(); // longitude
userRef.child(id + "/name").setValue(name);
userRef.child(id + "/token").setValue(refreshedToken);
userRef.child(id + "/latitude").setValue(my_lat);
userRef.child(id + "/longitude").setValue(my_long);
userRef.child(id + "/logged_in").setValue(true);
//if all matches then go onto the efar screen
errorText.setText("");
finish();
launchEfarScreen();
} else {
errorText.setText("ERROR: username or id is incorrect...");
}
} else {
Log.wtf("Login", "FAILURE!");
errorText.setText("ERROR: username or id is incorrect...");
}
}
@Override
public void onCancelled (DatabaseError firebaseError){
}
}
);
}
//disables the werid transition beteen activities
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
}