在服务XMPP连接会时,其过程完成后关闭 [英] Xmpp connection in service gets closed when its process is finished

查看:208
本文介绍了在服务XMPP连接会时,其过程完成后关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款Android聊天app.I还有一个活动,并在app.Here一个服务的服务包含了所有的连接功能和活动和服务之间的通信使用binder.My服务做在后台运行但是,当这个过程有一段时间我看到,在设置在emulator.I菜单已经看到了两个选项中提供两个解决这个首先是在一个单独的过程,我试图避免立即运行服务后,完成了连接会自动关闭。另一种是运行在一个单独的线程连接,但我需要有人来帮助我在这里为我不能做so.Here是我的code

I am developing a android chat app.I have an activity and a service in the app.Here the service contains all the connection function and the communication between the activity and service is done using a binder.My service is running in background but the connection gets closed automatically when the process is finished after some time i see that in setting menu in the emulator.I have seen two options two overcome this first is to run service in a separate process which i am trying to avoid for now.Another is to run connection in a separate thread but i need some one to help me here as i am unable to do so.Here is my code

    public class MainService extends Service{
private XMPPConnection connection;
private final IBinder mBinder = new MyBinder();

    @Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return mBinder;
}

    public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service","started");
new Connect().execute("");
return START_STICKY;
    }

    private class Connect extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
    ConnectionConfiguration connConfig = new ConnectionConfiguration(SERVICE,PORT);
    XMPPConnection connection = new XMPPConnection(connConfig);
    try {
        connection.connect();
        Log.i("XMPPChatDemoActivity",
                "Connected to " + connection.getHost());
    } catch (XMPPException ex) {
        Log.e("XMPPChatDemoActivity", "Failed to connect to "
                + connection.getHost());
        Log.e("XMPPChatDemoActivity", ex.toString());
        setConnection(null);
    }
    try {
        // SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        connection.login(USERNAME, PASSWORD);
        Log.i("XMPPChatDemoActivity",
                "Logged in as " + connection.getUser());

        // Set the status to available
        Presence presence = new Presence(Presence.Type.available);
        connection.sendPacket(presence);
        setConnection(connection);
        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        for (RosterEntry entry : entries) {
            Log.d("XMPPChatDemoActivity",
                    "--------------------------------------");
            Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
            Log.d("XMPPChatDemoActivity",
                    "User: " + entry.getUser());
            Log.d("XMPPChatDemoActivity",




        "Name: " + entry.getName());
            Log.d("XMPPChatDemoActivity",
                    "Status: " + entry.getStatus());
            Log.d("XMPPChatDemoActivity",
                    "Type: " + entry.getType());
            Presence entryPresence = roster.getPresence(entry
                    .getUser());

            Log.d("XMPPChatDemoActivity", "Presence Status: "
                    + entryPresence.getStatus());
            Log.d("XMPPChatDemoActivity", "Presence Type: "
                    + entryPresence.getType());
            Presence.Type type = entryPresence.getType();
            if (type == Presence.Type.available)
                Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
            Log.d("XMPPChatDemoActivity", "Presence : "
                    + entryPresence);

        }
    } catch (XMPPException ex) {
        Log.e("XMPPChatDemoActivity", "Failed to log in as "
                + USERNAME);
        Log.e("XMPPChatDemoActivity", ex.toString());
        setConnection(null);
    }
    return null;       
}}

    public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
    // Add a packet listener to get messages sent to us
    PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
    connection.addPacketListener(new PacketListener() {
        public void processPacket(Packet packet) {
            Message message = (Message) packet;
            if (message.getBody() != null) {
                String fromName = StringUtils.parseBareAddress(message
                        .getFrom());
                Log.i("XMPPChatDemoActivity", "Text Recieved " + message.getBody()
                        + " from " + fromName );
            }
        }
    }, filter);
}
    }

   public class MyBinder extends Binder 
    {
        MainService getService() {
        return MainService.this;
      }
      }

    public XMPPConnection getconnection()
    {
if (connection != null) {
    Log.d("MainService","connection send");
    return connection;  
}
else
{
    Log.d("MainService","connection null");
return null;    
}

}
}

} }

    public class XMPPChatDemoActivity extends Activity {
private MainService service;
private XMPPConnection connection;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    if(!isMyServiceRunning())  
    {
    startService(new Intent(this,MainService.class));
    }
    }
 @Override
  protected void onResume() {
    bindService(new Intent(this, MainService.class), mConnection,
        Context.BIND_AUTO_CREATE);
    super.onResume();
  }

  @Override
  protected void onPause() {
    unbindService(mConnection);
    super.onPause();
  }
     private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder binder) {
          service = ((MainService.MyBinder) binder).getService();
          Log.d("Service","Connected");
          Toast.makeText(XMPPChatDemoActivity.this, "Connected",                              Toast.LENGTH_SHORT)
              .show();
            connection=service.getconnection();
        }

        public void onServiceDisconnected(ComponentName className) {
            connection=null;
            service = null;
        }
      };
private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (MainService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

}

推荐答案

不处理该问题:机器人杀死服务时,资源却越来越低。通常情况下,你可以通过解决这个问题。

Both of you mentioned seemingly solution don't approach the issue: Android kills services when its resources are getting low. Typically you can fix this by either


  1. 标记的服务为前台的(在这种情况下不建议 1

  1. Marking the service as foreground (In this case not recommended1)

标记的服务为 STICKY ,以便它得到的是被杀害后重新启动

Marking the service as STICKY so that it get's restarted after it got killed

我真的建议使用 STICKY 办法。运行带有前台活动相关的服务,AU更简单,因为你只需要添加只有一行额外的code,但它也prevents从Android的释放迫切需要的其他地方的资源。如果您服务为前台运行,并遭受形式内存泄漏或有其他一些原因,高内存使用情况,设备将变得缓慢而Android是无法修复这种情况。

I really recommend using the STICKY approach. Running a service with foreground activity ,au be simpler, because you simply have to add only one line of extra code, but it also prevents Android from releasing resources that are urgently needed somewhere else. If you service runs as foreground and suffers form memory-leaks or has for some other reason high memory usage, the device will become slow and Android is unable to fix this situation.

因此​​,最好的办法是,以纪念你的服务STICKY ,并恢复它的状态,一旦它得到重新启动。所有优秀的Andr​​oid的XMPP客户端做到这一点。

Therefore the best approach is to mark your service as STICKY and restore it's state once it got restarted. All good Android XMPP clients do that.

1:前景的服务旨在提供服务的地方会导致糟糕的用户体验,例如重启如果音乐播放器服务被重新启动时,用户将注意到它。这就是标志着服务作为前景为宜典型的例子。

这篇关于在服务XMPP连接会时,其过程完成后关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆