Smack Android, creating a service to receive messages

I'm doing a chat with the library smack Android 4.1.4. This library uses the XMPP protocol. To receive messages, you must authenticate to a server (for example openfire) and login using XMPPCONNECTION. All of this is quite simple if performed when the application starts. The problem comes when you have to receive messages when the application is closed. I tried to use an "Android service" to maintain this alive the connection between the client and the server. (In this case I did) but I do not think is the best method. Also because Android through service when the phone is switched off and on again the service does not restart by itself, and messages received while the phone was switched off will be lost. I attach the code Android. Do you have any advice ?. It would be useful to know how to do other chat applications such as whatsapp, badoo, facebook, telegram, etc ..

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 {

                        }




                    }

                });

            }

        });


}


}

Actually i am not solve yet this kind of stuff. But, i do way to change BackgroundService to ForegroundService for this case. Remember this will not solve any Android devices.

Unlike whatsapp, telegram, fb. They play in Native C (NDK) to force OS which permit app to run in backgroundservice.

You can dive in Telegram Source Code for this issue.

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

上一篇: 获取定制XMPP服务器有多简单?

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