如何在Android聊天应用程序处于后台时接收消息作为通知

时间:2016-03-09 05:25:45

标签: android socket.io

我正在开发一个Android即时聊天应用程序。我已经使用socket.io-client库实现了它。这里的一切正常。当应用程序将被不同设备上的不同用户使用时,可以使用套接字将消息从一个用户发送到另一个用户。但这只有在应用程序处于活动状态。如果应用程序在另一端未处于活动状态,则说明它无法正常工作。我想通知用户该消息是否已经像WatsApp那样到达。如何使用套接字实现此目的。

以下是我的听众的代码:

 mSocket.on("send:notice", onReceive); // Listening event for receiving messages

 // Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        Log.e("Receive", "Bean_Message received");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                Log.e("DATA", String.valueOf(data));
                try {
                    JSONArray ops = data.getJSONArray("ops");
                    Log.e("JSONArray", ops.toString());
                    for (int i = 0; i < ops.length(); i++) {
                        JSONObject object = ops.getJSONObject(i);
                        String roomID = object.getString("room_id");
                        Log.e("RoomID", roomID); // Getting room ID from JSON array
                        Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
                        //Comparing the room IDs
                        if (md5StringRoomID.equals(roomID)) {
                            String senderName = object.getString("user");
                            Log.e("Sender Name", senderName);
                            String senderID = object.getString("id");
                            Log.e("SenderID", senderID);
                            String date = object.getString("date"); // Getting timestamp value in the form of string
                            long time = Long.parseLong(date); //Converting String into long
                            String t = getDateFromTimestamp(time); // Getting date and time from timestamp
                            Log.e("DateReceived", date);
                            // JSONObject message = object.getJSONObject("message");
                            String unicodeMessageReceived = object.getString("message");
                            Log.e("UnicodeMessageReceived", unicodeMessageReceived);
                            //Decoding unicode characters for emoji
                            String messageReceived = StringEscapeUtils.unescapeJava(unicodeMessageReceived);
                            Log.e("DecodedMessageReceived", messageReceived);
                            String loggedInUSerNAme = sharedPreferences.getString(Prefs_Registration.get_user_name, null);
                            //String loggedInUSerNAme = almaChatDatabase.getUserName();
                            //If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
                            if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
                                isSelf = true;
                                msg = new Bean_Message(senderName, messageReceived, isSelf);
                                msg.setMessageStatus(Status.SENT);
                                msg.setTime(t);
                                listBeanMessages.add(msg);
                                // Log.e("List Elements", String.valueOf(listBeanMessages));
                                adapter_message.notifyDataSetChanged();
                                playBeep();
                            } else {
                                isSelf = false;
                                msg = new Bean_Message(senderName, messageReceived, isSelf);
                                msg.setTime(t);
                                listBeanMessages.add(msg);
                                Log.e("List Elements", String.valueOf(listBeanMessages));
                                adapter_message.notifyDataSetChanged();
                                playBeep();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // Playing sound when the message is sent by other
    public void playBeep() {
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

};

我必须处理两个通知案例: 1.当应用程序处于后台时 2.当应用程序处于前台但用户A忙于用户B时,来自用户C的消息到达。

请帮我解决问题。

3 个答案:

答案 0 :(得分:2)

1)一种方法是 你应该在应用程序启动时使用START_STICKY运行自己的服务,并且在该服务内部必须启动一个线程。供参考,请参阅服务http://developer.android.com/intl/es/reference/android/app/Service.html

的android文档

2)另一种方法是使用GCM推送通知。在onResume()和onPasue()中,即在前台onResume()连接到socket.io服务器,如果用户进入后台,则断开用户与socket.io server.if用户的连接从socket.io服务器断开连接到GCM推送通知,通知用户。

答案 1 :(得分:1)

按照http://developer.android.com/guide/components/bound-services.html所述创建后台服务, 写入此服务中的套接字连接代码并从启动器活动启动服务,并通过从其他活动绑定服务来使用该服务

答案 2 :(得分:0)

试试这个:

public Emitter.Listener handleIncomingMessages = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                String message = null;
                String imageText;
                try {
                    message = data.getString("message").toString();
                  Log.v("messageeeeeeeeeee",message);

                } catch (JSONException e) {
                    // return;
                }

                addMessage(message);

                try {
                    imageText = data.getString("image");
                    addImage(decodeImage(imageText));
                } catch (JSONException e) {
                    //retur
                }
            }
        });
    }
};