Smack Android,创建接收消息的服务

时间:2015-11-15 13:09:10

标签: java android xmpp chat smack

我正在和图书馆的Android 4.1.4聊天。该库使用XMPP协议。要接收消息,您必须对服务器进行身份验证(例如openfire)并使用XMPPCONNECTION进行登录。如果在应用程序启动时执行,则所有这些都非常简单。当应用程序关闭时您必须接收消息时会出现问题。我试图使用“Android服务”来维持客户端和服务器之间的连接。 (在这种情况下,我做了)但我认为不是最好的方法。此外,由于Android通过服务,当手机关闭再打开时,服务不会自动重启,并且手机关机时收到的消息将丢失。我附上Android代码。你有什么建议吗?知道如何做其他聊天应用程序如whatsapp,badoo,facebook,telegram等会很有用。

public class ServizioMessaggi extends Service {

public static final int NOTIFICATION_ID = 1;
static ChatManager chatmanager;
public static AbstractXMPPConnection connessione;
ConnettiServizio connetti;
MySQLiteHelper db;
String SharedPreferences = "Whisper";

public ServizioMessaggi() {
    super();
}

@Override
public void onCreate() {

    SharedPreferences sharedPref = getSharedPreferences(SharedPreferences, Context.MODE_PRIVATE);
    connetti = new ConnettiServizio();
    connetti.execute(sharedPref.getString("username",""),sharedPref.getString("password",""),"vps214588.ovh.net");
    db = new MySQLiteHelper(this);



    super.onCreate();
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}


@Override
public void onDestroy() {
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public class ConnettiServizio extends AsyncTask<String,String,String> {
    public AbstractXMPPConnection con;
    @Override
    protected String doInBackground(String... strings) {
        con = new XMPPTCPConnection(strings[0],strings[1],strings[2]);
        try {
            con.connect();
            con.login();
        } catch (SmackException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        connessione = con;

        con.addConnectionListener(new ConnectionListener() {
            @Override
            public void connected(XMPPConnection connection) {
                System.out.println("connected");
            }

            @Override
            public void authenticated(XMPPConnection connection, boolean resumed) {
                System.out.println("autenticathed");
            }

            @Override
            public void connectionClosed() {
                System.out.println("Connection Close");
            }

            @Override
            public void connectionClosedOnError(Exception e) {
                System.out.println("Connection Close whith error");
            }

            @Override
            public void reconnectionSuccessful() {
                System.out.println("reconnection ");
            }

            @Override
            public void reconnectingIn(int seconds) {

            }

            @Override
            public void reconnectionFailed(Exception e) {
                System.out.println("recconnection failed");
            }
        });

        ascolta();

    }
}

private void ascolta() {

    chatmanager = ChatManager.getInstanceFor(connetti.con);

        chatmanager.addChatListener(new ChatManagerListener() {


            public void chatCreated(final Chat chat, final boolean createdLocally) {

                Log.i("chat creata", "****************");

                chat.addMessageListener(new ChatMessageListener() {


                    public void processMessage(Chat chat, Message message) {



                        Log.i("messaggio arrivato", "****************");

                        //JOptionPane.showMessageDialog(null, "Rec: For " + chat.getParticipant() + " from " + message.getFrom() + "\n" + message.getBody());

                        String sender = message.getFrom();


                        System.out.println("Received message: " + (message != null ? message.getBody() : "NULL"));

                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                        Intent notificationIntent = new Intent(ServizioMessaggi.this, Chat.class);

                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

                        PendingIntent intent = PendingIntent.getActivity(ServizioMessaggi.this, 0,
                                notificationIntent, 0);

                        // scelta suoneria per notifica
                        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

                        NotificationCompat.Builder mBuilder =
                                (NotificationCompat.Builder) new NotificationCompat.Builder(ServizioMessaggi.this)
                                        .setSmallIcon(R.drawable.ic_stat_notification)
                                        .setColor(Color.argb(0,0,176,255))
                                        .setTicker("Nuovo messaggio da " + message.getFrom())
                                        .setContentTitle(sender.substring(0,sender.indexOf("@")))
                                        .setContentText(message.getBody())
                                        .setContentIntent(intent)
                                        .setSound(sound);

                        // effettua la notifica
                        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());




                        SimpleDateFormat s = new SimpleDateFormat("hh:mm:ss");
                        String ora = s.format(new Date());

                        //aggiungo il messaggio al database
                        Messaggio ms = new Messaggio();
                        ms.setUsername(message.getFrom().substring(0, message.getFrom().indexOf("/")));
                        ms.setIsmy("no");
                        ms.setTimestamp(ora);
                        ms.setMessaggio(message.getBody());
                        db.addMessaggio(ms);


                        if(ChatActivity.isvisible){

                            ((Activity)ChatActivity.c).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ChatActivity.updateListMessaggi();
                                }
                            });
                        } else {

                        }




                    }

                });

            }

        });


}


}

2 个答案:

答案 0 :(得分:1)

实际上我还没有解决这种问题。但是,我确实在这种情况下将BackgroundService更改为ForegroundService。请记住,这不会解决任何Android设备。

与whatsapp,telegram,fb不同。它们使用Native C(NDK)来强制操作系统允许应用程序在后台服务中运行。

您可以针对此问题深入了解Telegram源代码。

答案 1 :(得分:0)

  
      
  • 当应用关闭时,我们无法维持连接。
  •   

您必须通过推送通知接收消息。然后将其重新连接到服务器...