XMPP服务连接死亡

时间:2014-03-09 10:50:49

标签: java android service xmpp chat

我正在用Java开发一个Android聊天应用程序。现在我终于得到了我的服务,但是一旦我完全杀死了应用程序,我服务中的连接就会消失。

我使用asmack作为XMPP连接的库。目标是即使应用程序被用户杀死也会收到消息(因此它不在后台)。

当我使用前台服务时, 工作,但我不想使用前台服务,因为内存使用率很高,而且我不想在通知中心使用前台消息

我的服务类

public class MessagingService extends Service {

private final String TAG = "MessagingService";
private final IBinder mBinder = new MessagingBinder();
public Context context;
public XMPPConnection Connection;
public static Handler mHandler = new Handler();

private final int ONGOING_NOTIFICATION_ID = 2344;

@Override
public void onCreate() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind");
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    Log.d(TAG, "onUnbind");
    return true;
}

@Override
public void onRebind(Intent intent) {
    super.onRebind(intent);
    Log.d(TAG, "onRebind");
}

@Override
public void onDestroy() {
}


public class MessagingBinder extends Binder {

    MessagingService getService() {
        Log.d(TAG + " - MessagingBinder", "getService");
        return MessagingService.this;
    }

}

public Boolean isConnected() {
    return (Connection != null);
}

public void Connect(final AuthorizeActivity authorize, final String username, final String password) {
    Thread XMPPConnect = new Thread(new Runnable() {

        public final String TAG = "XMPPConnect Thread";

        @Override
        public void run() {

            AndroidConnectionConfiguration connConfig = new AndroidConnectionConfiguration(Configuration.HOST, Configuration.PORT, Configuration.SERVICE);

            SmackConfiguration.setDefaultPingInterval(100);
            connConfig.setReconnectionAllowed(true);
            connConfig.setSASLAuthenticationEnabled(true);
            connConfig.setRosterLoadedAtLogin(true);

            Connection = new XMPPConnection(connConfig);

            try {
                Connection.connect();
                Log.i(TAG, "Connected to " + Connection.getHost());
            } catch (XMPPException ex) {
                Log.e(TAG, "Failed to connect to " + Connection.getHost());
                Log.e(TAG, ex.toString());
                Connection = null;
            }

            if(authorize != null)
                authorize.mServiceConnectCallback();

            if(username != null && password != null)
                Login(username, password, null);

        }

    });
    XMPPConnect.start();
}

public void Login(final String username, final String password, final AuthorizeActivity authorize) {
    Thread XMPPLogin = new Thread(new Runnable() {

        public final String TAG = "XMPPConnect Thread";

        @Override
        public void run() {

            try {
                Connection.login(username, password);
                Log.i(TAG, "Logged in as " + Connection.getUser());

                Presence presence = new Presence(Presence.Type.available);
                Connection.sendPacket(presence);

                PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
                Connection.addPacketListener(new PacketListener() {
                    @Override
                    public void processPacket(Packet packet) {
                        final Message message = (Message) packet;
                        if (message.getBody() != null) {
                            final String fromName = StringUtils.parseName(message.getFrom());
                            Log.i(TAG, "Text Recieved " + message.getBody() + " from " + fromName );

                            mHandler.post(new Runnable() {
                                public void run() {
                                    Receiver.recieveMessage(fromName, message.getBody());

                                    if(!VisibilityHelper.IsVisible()) {
                                        showNotification(fromName, message.getBody());
                                    }

                                }
                            });
                        }
                    }

                }, filter);

            } catch (XMPPException ex) {
                Log.e(TAG, "Failed to log in as " + "test");
                Log.e(TAG, ex.toString());
                Connection = null;
            }

            if(authorize != null)
                authorize.mServiceLoginCallback();

        }

    });
    XMPPLogin.start();
}

public void showNotification(String from, String message) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    CharSequence notiText = message;
    long meow = System.currentTimeMillis();

    Notification notification = new Notification(R.drawable.ic_launcher, notiText, meow);

    Context context = getApplicationContext();
    CharSequence contentTitle = from;
    CharSequence contentText = message;
    Intent notificationIntent = new Intent(context, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;

    int SERVER_DATA_RECEIVED = 1;
    notificationManager.notify(SERVER_DATA_RECEIVED, notification);
}

public void Logout() {
    if(Connection.isConnected()) {
        Log.i(TAG, "Logout");
        Connection.disconnect();
    }
}

public HashMap<String, String> getVCard(String user) {
    Log.d(TAG, "getVCard");

    //String email = user + "@" + Configuration.HOST;
    String email = user;

    VCard card = new VCard();

    ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider());

    try {
        card.load(MainActivity.mService.Connection, email);

        String jabber_id = card.getJabberId();
        String firstname = card.getFirstName();
        String middlename = card.getMiddleName();
        String lastname = card.getLastName();

        HashMap<String, String> vcard = new HashMap<String, String>();

        vcard.put("jabber_id", jabber_id);
        vcard.put("firstname", firstname);
        vcard.put("middlename", middlename);
        vcard.put("lastname", lastname);

        return vcard;
    } catch (XMPPException e) {
        e.printStackTrace();
    }

    return null;
}

public void retrieveContactsFromList() {
    if(this.isConnected()) {
        Roster roster = Connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();

        for(RosterEntry entry : entries) {
            Receiver.onRetrieveContactFromList(entry);
        }
    }
}

}

我启动服务的活动

public class ConnectionBinder extends FragmentActivity {

private final String TAG = "ConnectionBinder";
public static MessagingService mService;
public boolean mBound = false;

public Database DB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(!this.messagingServiceIsRunning())
    {
        startService(new Intent(this, MessagingService.class));
    }
}

private boolean messagingServiceIsRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (MessagingService.class.getName().equals( service.service.getClassName())) {
            return true;
        }
    }

    return false;
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private void doBindService() {
    Intent intent = new Intent(this, MessagingService.class);
    bindService(intent, mMessagingService, Context.BIND_AUTO_CREATE);
}

private void doUnbindService() {
    if (mBound) {
        unbindService(mMessagingService);
    }
}

private void doXMPPLogin() {
    HashMap<String, String> user = DB.getUser();

    mService.Connect(null, user.get("username"), user.get("password"));
}

private ServiceConnection mMessagingService = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        Log.d(TAG, "mMessagingService.onServiceConnected()");
        MessagingBinder binder = (MessagingBinder) service;
        mService = binder.getService();
        mBound = true;

        if(!mService.isConnected()) {
            doXMPPLogin();
        }

        mService.retrieveContactsFromList();
    }

    public void onServiceDisconnected(ComponentName arg0) {
        Log.d(TAG, "mMessagingService.onServiceDisconnected()");
        mBound = false;
    }

};

}

1 个答案:

答案 0 :(得分:4)

传统的XMPP实现(和XMPP RFC)没有定义维护持久用户&#34;会话的方法。当客户端断开连接时 - 当基础TCP / IP或HTTP连接丢失时,它们都会关闭用户会话。 另一方面,典型的Android环境有&#34;始终连接&#34; Google云服务,即使未连接,也可以为您的应用提供消息。实际上,大多数聊天和社交网络应用程序都使用GCM来通知用户有关新消息的信息。 因此,根据您的需求,您需要在聊天应用程序的服务器端进行一些更改:

  1. 大多数XMPP服务器实现都能够存储用户离线时收到的消息&#34;离线&#34;并在用户再次连接时提供。你可以&#34;勾解&#34;离线消息接收并通过Google Cloud Messaging通知用户有关新消息的可用性,用户将在再次打开您的应用程序时收到该消息,并且您的XMPPConnection将建立​​。
  2. 使用XMPP Stream Management扩展程序 - 如果您需要跨多个用户重新连接共享同一会话 - 并且&#34; resume&#34;用户再次打开您的应用时的上一个会话你仍然应该告诉用户他的&#34;会话&#34;中的新事件。通过GCM。
  3. 您的服务器端XMPP软件应为每个用户设备保留GCM注册ID,因此当用户设备在GCM中注册时 - 您需要通知服务器有关新注册的ID - 可以通过发送自定义&lt; iq&gt;来实现。使用您的GCM ID发送到服务器的数据包。
  4. 某些商业XMPP产品已经实施了上述步骤,并将向您推销&#34;支持推送的XMPP服务&#34;实际上,正如我所描述的那样,它实际上是带有GCM后端的XMPP服务器。