2017-11-08 10 views
0

私は、ユーザーが互いに通信できるようにするメッセージアプリケーションを作成しました。私はこれを行うためにFirebaseを使用しています。今問題は、バックグラウンドで通知を作成する(アプリがバックグラウンドであるか閉じているか)。メッセンジャー/ whatsappと同様に、未読メッセージの通知を受け取ります。チャットアプリケーションの通知SERVICEを作成する方法は?

これはどのように作成できますか?あなたは今ではさらに簡単に(Google App Engineの上など)のインスタンスを提供し、アプリを実行したりするのいずれか必要がありますクライアントにプッシュ通知を送信するために

chat-room.java

public class Chat_Room extends AppCompatActivity{ 

private Button btn_send_msg; 
private EditText input_msg; 
private TextView chat_conversation; 

private String user_name,room_name; 
private DatabaseReference root ; 
private DatabaseReference Mnotification; 
private String temp_key; 


NotificationCompat.Builder notification; 
private static final int uniqueID = 1995; 

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

    btn_send_msg = (Button) findViewById(R.id.btn_send); 
    input_msg = (EditText) findViewById(R.id.msg_input); 
    chat_conversation = (TextView) findViewById(R.id.textView); 







    user_name = getIntent().getExtras().get("user_name").toString(); 
    room_name = getIntent().getExtras().get("room_name").toString(); 
    setTitle(" Room - "+room_name); 

    root = FirebaseDatabase.getInstance().getReference().child(room_name); 
    Mnotification = FirebaseDatabase.getInstance().getReference().child("notifications"); 

    btn_send_msg.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      Map<String,Object> map = new HashMap<String, Object>(); 
      temp_key = root.push().getKey(); 
      root.updateChildren(map); 

      DatabaseReference message_root = root.child(temp_key); 
      Map<String,Object> map2 = new HashMap<String, Object>(); 
      map2.put("name",user_name); 
      map2.put("msg",input_msg.getText().toString()); 

      message_root.updateChildren(map2); 
      //not(); 
      //test(); 

     } 
    }); 

    root.addChildEventListener(new ChildEventListener() { 
     @Override 
     public void onChildAdded(DataSnapshot dataSnapshot, String s) { 

      append_chat_conversation(dataSnapshot); 

     } 

     @Override 
     public void onChildChanged(DataSnapshot dataSnapshot, String s) { 

      append_chat_conversation(dataSnapshot); 

     } 

     @Override 
     public void onChildRemoved(DataSnapshot dataSnapshot) { 

     } 

     @Override 
     public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 

    }); 




} 


public void test() { 

    String tkn = FirebaseInstanceId.getInstance().getToken(); 
    String text = chat_msg; 
    not(); 
    Log.d("App", "Token[" + tkn + "]"); 





} 


public void not(){ 



    notification = new NotificationCompat.Builder(this); 
    notification.setAutoCancel(true); 

    notification.setSmallIcon(R.drawable.downloadfile); 
    notification.setTicker("This is the tocken"); 
    notification.setWhen(System.currentTimeMillis()); 
    notification.setContentTitle(user_name); 
    notification.setContentText(chat_msg); 


    Intent intent = new Intent(Chat_Room.this, Message.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    notification.setContentIntent(pendingIntent); 


    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    nm.notify(uniqueID, notification.build()); 





} 

private String chat_msg,chat_user_name; 

private void append_chat_conversation(DataSnapshot dataSnapshot) { 

    Iterator i = dataSnapshot.getChildren().iterator(); 

    while (i.hasNext()){ 

     chat_msg = (String) ((DataSnapshot)i.next()).getValue(); 
     chat_user_name = (String) ((DataSnapshot)i.next()).getValue(); 












     chat_conversation.append(chat_user_name +" : "+chat_msg +" \n"); 
     input_msg.setText(""); 
     test(); 





    } 



} 

}

答えて

0

関数を介してFirebase関数があります。簡単に言えば、要求に反応して通知を送信するサーバー上でコードを実行する必要があります。

すでにFirebaseデータベースを使用しているため、Firebaseの機能が最も簡単な方法であることがわかりました。関数を記述して展開する必要があります。

--> firebase deploy --only functions 

新しいデータが書き込まれる(onCreate())たびに更新され、データベースから削除された場合でも、関数がトリガーされます。 (新しいメッセージがデータベースの "messages"ノードに書き込まれるたびにトリガーするような関数を書くと想像してください)。

はまた、あなたが通知を送信するためにあなたの機能で、後でそれを必要とするため、データベース内のユーザーに「トークン」生成されたSクライアント側をユニークなメッセージを格納する必要があります。関数では、データベースからそのトークンを取得し、SDK経由で通知を送信する必要があります。

//your imports ; see sample linked below for a complete example 
//imagine your functions is triggered by any new write in "messages" node in your database 
exports.sendNotification = functions.database.ref('/messages/{keyId}').onWrite(

     //get the token that is already saved in db then ; 
     const payload = { 
     notification: { 
     title: 'You have a new follower!', 
     body: `${follower.displayName} is now following you.`, 
     icon: follower.photoURL 
     } 
     }; 

     admin.messaging().sendToDevice(tokens, payload); //which is a promise to handle 

}); 

サンプルについてFirebase機能を経由して通知を送信するにHereを参照してください。ここで私が説明したものを簡略化コードがありますFirebase関数サンプルについては、Hereを参照してください。 Firebaseの機能とトリガの詳細については、hereを参照してください。

さらに詳しい説明については、here(Firebaseの機能の前に書かれていたことに注意してください)を参照してください。そのため、アプリケーションサーバーのインスタンスにデプロイすることを前提としています。また、hereは、通知を送信するためのクラウド機能(Firebase機能)の使用に関する詳細です。

+0

私は、デバイスがfirebaseで?だから、管理者が3つの部門の責任者であり、彼が送信したいと言うことができますことを、私はどのようにするだろう、例えば特定の部門内のユーザーのリストが含まれているリストビューに通知を送信する場合各部門の各ユーザーリストへの通知 –

+0

各部門のユーザーのリストがある限り、上記の回答と同じになります。トークンをループして通知するだけです。あなたのシナリオが何か違うかどうかは分かりません。あなたのアプリケーションのすべてのユーザに通知を送信することも、Firebaseコンソールから通知をチャンクに分割することもできます。 – TheeBen

+0

はいデバイスを使用している人が、デバイスが複数のデバイス通知のように動作しているかどうかわからないユーザに彼が書いた通知を送信したい場合 –

関連する問題