Android服务在活动结束时结束并重新打开

时间:2015-06-04 18:03:41

标签: android service

我有一个服务,我从这样的新线程开始:

@Override
protected void onStart() {
    super.onStart();
    Thread t = new Thread(){
        public void run(){
            Intent in = new Intent(getApplicationContext(),MessagingService.class);
            startService(in);
        }
    };
    t.start();
}

它维护用于推送消息传递的TCP连接。一切正常,直到我在最近的应用程序菜单中向左滑动应用程序才能关闭。

当应用关闭时,连接会被删除并立即重新连接。阅读日志:

06-04 20:57:01.735  15238-15238/com.test.app V/MessagingService﹕ onStartCommand()
06-04 20:57:02.065  15238-15238/com.test.app I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@425e4220 time:99066408
06-04 20:57:05.145  15238-15238/com.test.app W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
06-04 20:57:10.635  15795-15795/com.test.app D/ActivityThread﹕ handleBindApplication:com.test.app
06-04 20:57:10.635  15795-15795/com.test.app D/ActivityThread﹕ setTargetHeapUtilization:0.75
06-04 20:57:10.635  15795-15795/com.test.app D/ActivityThread﹕ setTargetHeapMinFree:2097152
06-04 20:57:10.685  15795-15795/com.test.app V/MessagingService﹕ onStartCommand() 

为什么在应用“关闭”时会再次调用onStartCommand()(这不是强制关闭)。有没有办法让它顺利运行?

1 个答案:

答案 0 :(得分:0)

我认为您应该使用IntentService在新主题中运行Service。

相关问题