我正在使用IntentService
實施基於聊天的應用程序。現在我需要獲得消息,即使應用程序不在後臺。很明顯,我想要的是我需要運行意向服務,如果應用程序不處於後臺狀態。如何運行意向服務甚至應用程序被殺害/銷燬
public class ChatService extends IntentService {
JabberSmackAPI c = null;
XMPPConnection connection;
@Override
public void onCreate() {
super.onCreate();
System.out.println("chatservice------onCreate-----");
}
@Override
public int onHandleIntent(Intent arg0) {
System.out.println("--chat services--");
try {
setUp(c);
} catch (XMPPException e) {
// TODO Auto-generated catch block
System.out.println("--XMPPConnection error--chat service--");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("--IOException error--chat service--");
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void setUp(JabberSmackAPI c) throws XMPPException, IOException {
// declare variables
c = new JabberSmackAPI();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = "hi how r u!";
// Enter your login information here
c.login(chat_id, GlobalDeclaration.paswword);
System.out.println("-----");
String talkTo = "username";
}
public class JabberSmackAPI implements MessageListener, ChatManagerListener {
public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("Host", 5222);
connection = new XMPPConnection(config);
connection.connect();
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(packetListener, filter);
connection.login(userName, password);
}
}
private PacketListener packetListener = new PacketListener() {
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("In the process packet");
System.out.println(packet.toXML());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
getBaseContext().sendBroadcast(broadcastIntent);
System.out.println("---final packrt result-- " + packectResult.trim());
}
};
}
因此,運行意向服務的問題是什麼 – Mohit
如果應用程序在後臺/前臺運行,沒有問題。如果我殺了應用程序,我沒有收到消息。 – MinnuKaAnae
運行一個'服務',並把你的意圖在裏面... – Mohit