我尝试将收到的消息发送到我的Android手机以保存在firebase中。但它保存了最后收到的一个。似乎某种覆盖发生在firebase db上。你能帮我解决一下这个问题。提前谢谢
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by EngMohamed on 5/26/2017.
*/
public class SMSReciever extends BroadcastReceiver{
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
@Override
public void onReceive(Context context, Intent intent) {
//—get the SMS message passed in—
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String messages = "";
if (bundle != null)
{
//—retrieve the SMS message received—
Object[] smsExtra = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[smsExtra.length];
for (int i=0; i<msgs.length; i++)
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
//take out content from sms
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
}
putSmsToFirebase(sms,context);
}
}
public void putSmsToFirebase(SmsMessage sms, Context context)
{
String messageDate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
String messageBody = sms.getMessageBody().toString();
String messageSender= sms.getOriginatingAddress().toString();
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("messages");
mFirebaseDatabase.child("messagesender").push().setValue(messageSender);
mFirebaseDatabase.child("messagebody").push().setValue(messageBody);
mFirebaseDatabase.child("messagedate").push().setValue(messageDate);
}
}
答案 0 :(得分:0)
你的结构倒置了。我想你想要:
public void putSmsToFirebase(SmsMessage sms, Context context)
{
String messageDate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
String messageBody = sms.getMessageBody().toString();
String messageSender= sms.getOriginatingAddress().toString();
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("messages");
DatabaseReference messageRef = mFirebaseDatabase.push();
messageRef.child("messagesender").setValue(messageSender);
messageRef.child("messagebody").setValue(messageBody);
messageRef.child("messagedate").setValue(messageDate);
}
在上面messageRef
是数据库中存储新邮件的位置,然后在其下的属性中设置三个值。