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

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

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 {

                        }




                    }

                });

            }

        });


}


}

其实我还没有解决这种东西。 但是,我确实将BackgroundService更改为ForegroundService。 请记住,这不会解决任何Android设备。

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

你可以在这个问题中潜入电报源代码。

链接地址: http://www.djcxy.com/p/94087.html

上一篇: Smack Android, creating a service to receive messages

下一篇: Cannot maintain persistent XMPP connection from sticky service android