AsyncTask随机停止工作

时间:2014-10-09 11:44:59

标签: android eclipse android-asynctask

我有一个连接到XMPP的应用程序。每隔5分钟,我断开连接并重新连接(不要问,老板想要它......) - 到目前为止,我已经有AsyncTask在后​​台执行此操作,并且运行正常。然而,今天是一个不同的故事(请记住代码在相当长的一段时间内没有改变!并且通过SVN进行SC扫描,我检查过自上次发布以来没有发生任何变化)。

今天它会在5分钟后断开并启动连接,但只有在重新启动后才会启动。任何后续尝试都不会费心去尝试。

重新连接的runnable:

private final Runnable killConnection = new Runnable()
{
    @Override
    public void run()
    {
        synchronized(checkLock)
        {
            Log.d("BXC", "Killing connection and restarting");

            // Manually disconnect and restart the connection every 5 minutes
            destroyConnectionAndRestart();
            new LoginTask().execute();

            mHandler.postDelayed(this, mInterval5m);
        }
    }
};

AsynTask本身:

private class LoginTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params)
    {
        android.os.Debug.waitForDebugger();

        String deviceUsername = Utility.getAndroidID(GaggleApplication.getInstance());
        try
        {   
                //bConnecting = true;
                Log.d("BXC", "Beginning connection");
                synchronized(connectLock)
                {                   
                    // First ensure we've got a connection to work with first
                    if(Utility.hasActiveInternetConnection(getApplicationContext()) && 
                            ((!bConnecting) && (!Globals.backgroundXmppConnectorRunning)))
                    {                       
                        String randomResource = Utility.randomString();
                        setupConnection();

                        if(xConnection != null)
                        {
                            xConnection.connect();
                        }
                        else
                        {
                            bConnecting = false;
                            Globals.backgroundXmppConnectorRunning = false;
                            setupConnection();
                            xConnection.connect();
                        }

                        /*
                            I know, I know... Don't specify a resource, but more often than not, OpenFire, doesn't
                            specify a unique resource, so at least this way, if we disconnect and then reconnect, 
                            we're at least promised a resource that isn't being used already and leave OpenFire to 
                            remove it's own idle connections, after X minutes.
                         */                             
                        if(accountManager.supportsAccountCreation() && (!SystemProperties.getBoolean("accountCreated")))
                        {
                            Log.d("BXC", "Server supports registering custom user accounts");
                            accountManager.createAccount(deviceUsername, AppSettings.XMPP_KEYSTORE_PASSWORD);   
                            SystemProperties.setBoolean("accountCreated", true);
                        }

                        xConnection.login(deviceUsername, AppSettings.XMPP_KEYSTORE_PASSWORD, randomResource);                  
                        ChatManager.getInstanceFor(xConnection).addChatListener(new ChatManagerListener(){
                            @Override
                            public void chatCreated(final Chat chat, boolean createdLocally)
                            {
                                if(!createdLocally)
                                {
                                    // add chat listener //
                                    chat.addMessageListener(new BackgroundMessageListener(BackgroundXmppConnector.this));
                                }
                            }                           
                        });                 

                        Presence p = new Presence(Presence.Type.subscribe);
                        p.setStatus("Out and About");
                        xConnection.sendPacket(p);

                        mBuilder.setSmallIcon(android.R.drawable.presence_online)
                        .setContentTitle("Connected")
                        .setContentText("Connected to XMPP server");

                        mNotificationManager.notify(mNotificationId, mBuilder.build());

                        Roster r = xConnection.getRoster();                 
                        r.setSubscriptionMode(SubscriptionMode.accept_all);
                        r.createEntry(AppSettings.BOT_NAME, "AbleBot", null);
                        r.addRosterListener(new RosterListener(){

                            @Override
                            public void entriesAdded(Collection<String> addresses) 
                            {               
                                for(String s : addresses)
                                {
                                    Log.d("BXC", "Entries Added: " + s);
                                }
                            }

                            @Override
                            public void entriesDeleted(Collection<String> addresses) 
                            {
                                for(String s : addresses)
                                {
                                    Log.d("BXC", "Entries Deleted: " + s);
                                }                           
                            }

                            @Override
                            public void entriesUpdated(Collection<String> addresses) 
                            {   
                                for(String s : addresses)
                                {
                                    Log.d("BXC", "Entries updated: " + s);
                                }                           
                            }

                            @Override
                            public void presenceChanged(Presence presence) 
                            {   
                                Log.d("BXC", "PresenceChanged: " + presence.getFrom());
                            }                       
                        });
                    }   
                    else{
                        Log.i("BXC", "Already connected or in process of connecting. ");
                    }
            }
        }
        catch(IllegalStateException ex)
        {
            Log.e("BXC", "IllegalStateException -->");
            if(ex.getMessage().contains("Already logged in to server"))
            {
                Globals.backgroundXmppConnectorRunning = true;                      
            }
            else
            {
                Globals.backgroundXmppConnectorRunning = false;
                Utility.writeExceptionToLog(getApplicationContext(), ex);

                ex.printStackTrace();
            }
        }
        catch(XMPPException ex)
        {
            Log.e("BXC", "XMPPException -->");
            Globals.backgroundXmppConnectorRunning = false;
            Utility.writeExceptionToLog(getApplicationContext(), ex);
            ex.printStackTrace();
        }
        catch(NullPointerException ex)
        {
            Log.e("BXC", "NullPointerException -->");
            Globals.backgroundXmppConnectorRunning = false;
            Utility.writeExceptionToLog(getApplicationContext(), ex);
            ex.printStackTrace();
        }
        catch(Exception ex)
        {
            Log.e("BXC", "Exception -->");
            Globals.backgroundXmppConnectorRunning = false;
            Utility.writeToLog(getApplicationContext(), ex.toString());
            ex.printStackTrace();
        }               
        return null;
    }

    @Override
    protected void onPostExecute(Void ignored)
    {
        if(xConnection != null)
        {
            if(xConnection.isConnected() && (!xConnection.isSocketClosed()))
            {
                Log.i("BXC", "Logged in to XMPP Server");
                Globals.backgroundXmppConnectorRunning = true;

                ConnectionState cs = new ConnectionState(true);
                GaggleApplication.getBusInstance().post(cs);
                cs = null;

                // SEND A WHOAMI TO UPDATE DEVICE FRIENDLY NAME //
                WhoAmI wai = new WhoAmI();          
                Intent intent = new Intent(GaggleApplication.getInstance(), BackgroundXmppConnector.class);
                intent.putExtra("MESSAGEDATA", new Gson().toJson(
                        Utility.makeTransaction(GaggleApplication.getInstance(), MessageType.Type.WHOAMI, wai)));
                sendMessage(intent);
                Log.i("MAIN", "Sent WHOAMI transaction");                   

                mHandler.postDelayed(checkConnection, mInterval1m);
            }
            else
            {
                Log.e("BXC", "Unable to log into XMPP Server.");    
                Globals.backgroundXmppConnectorRunning = false;

                destroyConnectionAndRestart();
            }
        }
        else
        {
            Log.e("BXC", "Xmpp Connection object is null");
            Globals.backgroundXmppConnectorRunning = false;

            ConnectionState cs = new ConnectionState(false);
            GaggleApplication.getBusInstance().post(cs);
            cs = null;
        }
    }
}

我已尝试在此SO帖子的帮助下进行调试:How do I use the Eclipse debugger in an AsyncTask when developing for Android? - 如上所述,任何后续尝试都不会触发doInBackground - LogCat中没有任何相关内容1}}要么,我有点失落。

如果有人以前经历过这种情况,我们非常感谢您的帮助吗?

1 个答案:

答案 0 :(得分:0)

试试这种方式,它为我工作。

public void createXMPPConn() {
        Log.i(TAG, "creating connection");
        if (!NetworkUtil.isNetworkAvailable(getApplicationContext())) {
            return;
        }

        Thread conn = new Thread(new Runnable() {

            private String mPwd;

            @Override
            public void run() {
                do {
                    Log.i(TAG, "Trying to create connection");
                    try {
                        ConnectionConfiguration config = new ConnectionConfiguration(URLConstants.XMPP_HOST,
                                URLConstants.XMPP_PORT);
                        config.setSASLAuthenticationEnabled(false);
                        config.setSecurityMode(SecurityMode.disabled);
                        mXMPPCon = new XMPPConnection(config);
                        mPwd = csp.getString(StringConstants.PASSWORD, "");

                        mXMPPCon.connect();
                        Log.i(TAG, "Connected ");
                        if (!mPwd.equals("") && !mXMPPCon.isAuthenticated()) {
                            mXMPPCon.login(csp.getString(StringConstants.PHONE_NUMBER, ""), mPwd);
                            initIncomingChat(getApplicationContext());
                            setStatus(getmXMPPCon(), true, "");
                            sendBroadCastAsLoginSuccess();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // Rotate loop until app is not connected to XMPP and do
                    // login, if app is registered.

                } while (!mXMPPCon.isConnected() && !(mPwd.equals("") || mXMPPCon.isAuthenticated()));
            }

        });
        conn.start();

}

public void login(final XMPPConnection xmppCon, final IAuthenticationListener iAuthenticationListener,
            final String username, final String password) {

        Log.i(TAG, "login() " + username + " " + password);

        Thread loginThread = new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                try {
                    xmppCon.login(username, password);
                    Log.i(TAG, "LOGIN SUCCESS");
                    sendLoginSuccess(iAuthenticationListener);

                } catch (XMPPException e) {
                    Log.i(TAG, e.getMessage());
                    if (e.getXMPPError() != null && e.getXMPPError().getCode() == ErrorConstants.ERROR_SERVERDOWN) {

                    } else if (e.getXMPPError() != null
                            && e.getXMPPError().getCode() == ErrorConstants.ERROR_NOTCONNECTED) {

                    } else {

                    }
                    Log.i(TAG, "LOGIN FAILURE");
                    sendLoginFailure(iAuthenticationListener);

                } catch (IllegalStateException e) {
                    if (xmppCon.isAuthenticated()) {
                        sendLoginSuccess(iAuthenticationListener);
                    } else {
                        e.printStackTrace();
                        sendLoginFailure(iAuthenticationListener);
                    }
                }
                Looper.loop();
                try {
                    Thread.currentThread().join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        loginThread.start();

    }