2013-02-27 200 views
0

我有一个网络应用程序,它使用服务连接到其他对等方。当您使用“最近的应用程序”关闭应用程序时,它只会关闭进程,而不是service,这实际上并不坏,因为我想以这种方式。但是,下次用户打开应用程序时会产生一些麻烦。它崩溃,所以用户必须再次使用“Recent Apps”关闭up,然后再次尝试使用该应用。问题肯定是正在运行的服务,因为如果我在下次运行服务之前停止服务。它工作得很好!在应用程序启动时停止已启动的服务

其实这对我来说很奇怪,因为我没有在启动时启动另一个service。当用户点击一个按钮时,我开始它。无论如何,如果可能的话,最好的方法是能够使用正在运行的service,否则,我只想在我的应用程序启动时停止服务。

我是新来的Android和我被困在这一点:(

感谢您的帮助

回答

0

服务框架:

public class MyService extends Service { 
public static final String TAG = "MyServiceTag"; 
... 
} 

这是开始活动的一部分:

processStartService(MyService.TAG);

private void processStartService(final String tag) { 
Intent intent = new Intent(getApplicationContext(), MyService.class); 
intent.addCategory(tag); 
startService(intent); 
} 

这是停止活动的一部分:

processStopService(MyService.TAG); 

private void processStopService(final String tag) { 
Intent intent = new Intent(getApplicationContext(), MyService.class); 
intent.addCategory(tag); 
stopService(intent); 
} 
+0

这种做法会导致停止服务,每次用户离开应用程序。我想在应用程序关闭时停止它。我想如果我在服务内部检查应用程序进程没有运行,那么我可以停止服务,这是有道理的。你怎么看? – Peyman 2013-02-27 15:02:00

0

使用一个static对象这表明服务是否正在运行与否。

否则第二个选项,我发现How to check if a service is running on Android?

if(startService(someIntent) != null) { 
    Toast.makeText(getBaseContext(), 'Service is already running',Toast.LENGTH_SHORT).show(); 
}else { 
    Toast.makeText(getBaseContext(), 'There is no service running, starting service..', Toast.LENGTH_SHORT).show(); 
} 
+0

我做了类似的事情,但总比没有好,但第一次用户输入应用程序时,它崩溃了,所以他应该在最近的应用程序中选择它,它会工作,而如果我不这样做。用户必须关闭该应用程序,然后再次运行。所以我取得了一些成就,但这还不够!它应该每次应用程序启动时工作! – Peyman 2013-02-27 15:04:07

相关问题