Android 安卓-如何使用服务?

Android 安卓-如何使用服务?,android,service,Android,Service,第一次加载我的应用程序时,它会启动我的主要活动,在我的主要活动中,我会自动启动一项服务: Intent s = new Intent(this, Soc.class); startService(s); //start the service for the first time 我需要确保当用户下次打开应用程序时,它会终止旧服务,并重新创建服务: @Override //this code is on every activity in my application protected vo

第一次加载我的应用程序时,它会启动我的主要活动,在我的主要活动中,我会自动启动一项服务:

Intent s = new Intent(this, Soc.class);
startService(s);
//start the service for the first time
我需要确保当用户下次打开应用程序时,它会终止旧服务,并重新创建服务:

@Override
//this code is on every activity in my application
protected void onRestart()
{
     super.onRestart();
     Intent s = new Intent(this, Soc.class);
     stopService(s);
     //kill the service
     startService(s);
     //start a brand new service
}
这是终止服务和更新服务的正确方法吗

这是终止服务和更新服务的正确方法吗


嗯,这可能行得通,但相当浪费。在这种情况下,你为什么要为服务费心?或者,反过来说,为什么要销毁并重新创建服务来更新它?

因为我的服务是一个套接字,而我的应用程序是一个基于会话的应用程序。因此,为了使用应用程序,用户必须连接到服务器并请求一个新会话。@aryaxt:这与销毁和重新创建服务无关。是的,这是一个好主意,我关闭了套接字,并再次将其连接到服务器,而不是终止服务并重新创建它。