如何将 xmpp 侦听器添加到 android 中的服务?

Posted

技术标签:

【中文标题】如何将 xmpp 侦听器添加到 android 中的服务?【英文标题】:How to add xmpp listeners to services in android? 【发布时间】:2016-07-27 15:12:28 【问题描述】:

我正在开发 android 中的聊天(1 对 1)应用程序。我在服务器上使用 Smack api 和 jabber。

建立连接

使用 AsyncTask 我在应用程序启动时执行connection.connect().login(); 或当用户会话可用时。 XMPP Connection 由 dagger 提供。

XMPP 监听器

    连接监听器(中断时重新连接) 消息监听器(传入消息、状态),当应用不在前台时发送通知。

我最初的想法是设置一个包含消息侦听器的 IntentService,但我不确定如何将 IntentServices 设置为在应用程序上无限期运行的长期运行任务。

谢谢。

【问题讨论】:

【参考方案1】:

在服务中,您可以检查连接并断开连接,然后尝试再次登录。请参考以下代码。希望这能帮助您解决问题。

public class MyService extends Service 

public static final String ACTION_LOGGED_IN = "chatapp.loggedin";
private final LocalBinder binder = new LocalBinder();
XMPP xmppConnection;
private MessageHandler messageHandler;
private static String TAG = "MyService";


private void onLoggedIn() 

    FromMatchesFilter localFromMatchesFilter = null;
    try 
        localFromMatchesFilter = new FromMatchesFilter(JidCreate.domainBareFrom(Domainpart.from("livegroup@chatapp." + Common.SERVER_HOST)), false);
     catch (XmppStringprepException e) 
        e.printStackTrace();
    

    if(messageHandler == null)
        messageHandler = new MessageHandler(this);
    

   XMPP.getInstance().addStanzaListener(this, messageHandler);

    XMPP.getInstance().addChatListener(this, new ChatManagerListener() 
        @Override
        public void chatCreated(Chat chat, boolean createdLocally) 

        
    );

    XMPP.getInstance().configureSrvDeliveryManager(this);

    if(XMPP.getInstance().isFileTransferNegotiatorServiceEnabled())
        PurplkiteLogs.logError(TAG, "File Transfer Service is enabled");
    
    FileTransferNegotiator.IBB_ONLY = true;




public static boolean isMyServiceRunning(Context context) 
    ActivityManager manager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
            .getRunningServices(Integer.MAX_VALUE)) 
        if (MyService.class.getName().equals(
                service.service.getClassName())) 
            return true;
        
    
    return false;


public XMPP XMPP() 
    return this.xmppConnection;


public IBinder onBind(Intent paramIntent) 
    return this.binder;


Handler holdConnectionHandler = new Handler() 

    public void handleMessage(android.os.Message msg) 
        PurplkiteLogs.logInfo(TAG, "Service Handler Running");
        checkUserLogin();
        holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
    
;

private void checkUserLogin() 
    String user = AppSettings.getUser(MyService.this);

                XMPPTCPConnection connection = XMPP.getInstance().getConnection(MyService.this);
                if(connection != null)
                    connection.disconnect();
                
                if(XMPP.getInstance().isConnected())
                    XMPP.getInstance().close();
                
                final String user = AppSettings.getUser(MyService.this);
                final String pass = AppSettings.getPassword(MyService.this);
                final String username = AppSettings.getUserName(MyService.this);
                try 
                    XMPP.getInstance().login(user, pass, username);
                 catch (XMPPException e) 
                    e.printStackTrace();
                 catch (SmackException e) 
                    e.printStackTrace();
                 catch (IOException e) 
                    e.printStackTrace();
                 catch (InterruptedException e) 
                    e.printStackTrace();
                 catch (PurplKiteXMPPConnectException e) 
                    e.printStackTrace();
                



public void onCreate() 
    super.onCreate();
    PurplkiteLogs.logDebug(TAG, "in onCreate of Service");
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    this.xmppConnection = XMPP.getInstance();
    holdConnectionHandler.sendEmptyMessage(0);


    registerReceiver(new BroadcastReceiver() 
        public void onReceive(Context paramAnonymousContext,
                              Intent paramAnonymousIntent) 
            MyService.this.onLoggedIn();
        
    , new IntentFilter("chatapp.loggedin"));

    if ((AppSettings.getUser(this) != null)
            && (AppSettings.getPassword(this) != null)) 
        final String user = AppSettings.getUser(this);
        final String pass = AppSettings.getPassword(this);
        final String username = AppSettings
                .getUserName(MyService.this);

        new Thread(new Runnable() 
            public void run() 
                try 
                    XMPPTCPConnection connection=  MyService.this.xmppConnection.getConnection(MyService.this);
                    if(connection == null || !connection.isAuthenticated())
                        MyService.this.xmppConnection.login(user, pass,
                                username);
                    
                 catch (XMPPException e) 
                    PurplkiteLogs.logError(TAG, "Error in Login");
                    e.printStackTrace();
                
                catch (SmackException e) 
                    PurplkiteLogs.logError(TAG, "Error in Login");
                    e.printStackTrace();
                 catch (IOException e) 
                    PurplkiteLogs.logError(TAG, "Error in Login");
                    e.printStackTrace();
                 catch (InterruptedException e) 
                    PurplkiteLogs.logError(TAG, "Error in Login");
                    e.printStackTrace();
                 catch (PurplKiteXMPPConnectException e) 
                    PurplkiteLogs.logError(TAG, "Error in Login");
                    e.printStackTrace();
                
                MyService.this.sendBroadcast(new Intent(
                        "chatapp.loggedin"));
                return;
            
        ).start();
    



public class LocalBinder extends Binder 
    public LocalBinder() 
    

    public MyService getService() 
        return MyService.this;
    


谢谢

【讨论】:

以上是关于如何将 xmpp 侦听器添加到 android 中的服务?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用我的 android 应用在我的 xmpp 服务器中添加新用户?

线程安全地将数据从服务传递到活动 - Android

在 Android 中解除绑定后,如何让服务与听众保持活力?

Android Smack XMPP 节侦听器:缺少节属性

在 xmpp 中处理数据包侦听器

如何创建nodejs xmpp服务器和android xmpp客户端