即使应用关闭,也能保持服务的活力

时间:2014-05-24 07:29:02

标签: java android

我已经搜索但却一无所获。我的问题是:如何使我的服务在申请时不关闭。我有一个聊天应用程序所以即使应用程序关闭我也需要,服务一直在监听消息。

我试过了

 android:process=":my_process"

但是这会使服务变得像#34;一个单独的应用程序"从main等所以无法识别我的活动发送任何东西。

显然,我也不希望我的服务受到约束。

public class MyService extends Service {
public static final String HOST = "192.168.1.102";
  public static final int PORT = 5222;
  public static final String SERVICE = "reza-hp";
  public static final String USERNAME = "reza";
  public static final String PASSWORD = "pro";
  private ArrayList<String> messages = new ArrayList<String>();
  private Handler mHandler = new Handler();


  //public static Handler mHandler = new Handler();
public static  ConnectionConfiguration connConfig = new   
ConnectionConfiguration(HOST, PORT, SERVICE);
public static XMPPConnection connection = new XMPPConnection(connConfig);  
  //  ArrayList<String> messages = XMPPChatDemoActivity.messages; 

  @Override
public IBinder onBind(Intent intent) {

    return null;
}
// @Override
// public void onCreate() {
//  connect();  
//  setConnection(connection);
//this must be called again on reconnect
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub

BusProvider.getInstance().register(this);

 connect();


return START_STICKY;
}







public void connect() {


//  if (connection != null) {
//   final ProgressDialog dialog = ProgressDialog.show(this, "Connecting...", 
"Please wait...", false);
Thread t = new Thread(new Runnable() {
  @Override
  public void run() {
    // Create a connection
     try {
       connection.connect();
       Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to  
"+connection.getHost());
     } catch (XMPPException ex) {
         Log.e("XMPPChatDemoActivity",  "[SettingsDialog] Failed to connect to "+ 

connection.getHost());
         Log.e("XMPPChatDemoActivity", ex.toString());

    }


     try {
          if (!connection.isAuthenticated()) {

        connection.login(USERNAME, PASSWORD);
        Log.i("XMPPChatDemoActivity",  "Logged in as" + connection.getUser());
          }
        // Set the status to available
        Presence presence = new Presence(Presence.Type.available);
        try {
            connection.sendPacket(presence);
        } catch (NotYetConnectedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        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());

          }
   //       dialog.dismiss();
  }


  });
BusProvider.getInstance().post(new ButtonEvent());
t.start();
//  dialog.show();


}




 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() {
 @Override
     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);
        messages.add(fromName + ":");
        messages.add(message.getBody());
        Log.i("XMPPChatDemoActivity",message.getBody());
        mHandler.post(new Runnable() {
          public void run() {
    //        setListAdapter();
          }
        });
      }
    }
   }, filter);

  }
 }





}

1 个答案:

答案 0 :(得分:1)

  

粘性服务

是要走的路,这将使服务在被另一个进程杀死后自动启动

尝试以下

@Override
public int onStartCommand(Intent intent, int flags, int startId) { 
    // We want this service to continue running until it is explicitly stopped, so return sticky.       
   return START_STICKY;
 }

有关详细信息,请阅读文档:Here

希望这有帮助

相关问题