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

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

建立连接

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

XMPP 监听器

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

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

谢谢。

【问题讨论】:

    标签: android xmpp android-service


    【解决方案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;
        }
    }
    }
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 2022-08-03
      • 2013-02-17
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多