如何运行意图服务甚至应用程序被杀死/销毁

时间:2016-01-13 12:11:48

标签: android web-services xmpp chat intentservice

我正在使用IntentService实现基于聊天的应用。现在我需要获取消息,即使应用程序不在后台。显然我想要的是如果应用程序不处于后台状态,我需要运行intent服务。

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

}

4 个答案:

答案 0 :(得分:1)

您可以每隔X次添加一次警报,此警报可以触发服务。

解决方案1:闹钟 - 通话 - > BroadcastReceiver - Fire(开始) - >你的服务。

解决方案2:任何系统BroadcastReceiver(例如电池电平变化) - >你的服务。

-----更新-------

public class BaseNotificationManager extends BroadcastReceiver {


public static final String BaseAction = "Com.TST.BaseAction";
public static final String FireService = "Com.TST.FireNotificationAction";


private  static  final long timeFrame =  1000*60*5;  // 5 mints

public BaseNotificationManager() {
}

@Override
public void onReceive(Context context, Intent intent) {

    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
        /// add base alarm manager
        startBaseAlarmManager(context);

    }else  if (BaseAction.equals(intent.getAction())){
       //  StartYourService();
    } 
}       public  static  void startBaseAlarmManager (Context context){


    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, BaseNotificationManager.class);
    intent.setAction(BaseAction);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            5000,  timeFrame, alarmIntent);

}}

清单

<receiver
            android:name=".BaseNotificationManager"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

答案 1 :(得分:0)

基本上service正在您的背景中运行,即使您的应用已被杀死。

只需将服务称为

即可
 Intent chatService = new Intent(MainActivity.this,ChatService.class);
 startService(chatService);

答案 2 :(得分:0)

你应该startService和bindService 如果您只使用bindService,那么一旦您离开该类,它将被终止。 StartService将使您的服务保持活力。
如下:

Intent intentService = new Intent(MainActivity.this, MyService.class);
startService(intentService);
bindService(new Intent(MainActivity.this, MyService.class),MainActivity.this, BIND_AUTO_CREATE);

答案 3 :(得分:0)

尝试在onStartCommand中添加startForeground,它将提高服务的优先级。但它应该伴随着通知存在。

startForeground(int id, Notification notification)