Android:stopService在另一个Activity中

如何在另一项活动中停止我的服务?

我在summaryActivity中启动服务

SocketServiceIntent = new Intent(this, SocketService.class); SocketServiceIntent.putExtra("MessageParcelable", mp); startService(SocketServiceIntent); 

并从我的summaryActivity启动我的statusActivity

 Intent intent = new Intent(SummaryActivity.this, StatusActivity.class); intent.putExtra("MessageParcelable", mp); startActivity(intent); 

我的问题是,我不知道如何可以给我的状态活动SocketServiceIntent。

你应该调用Activity(ContextWrapper)#stopService

 stopService(new Intent(SummaryActivity.this, SocketService.class)); 

你还没有解释你目前如何使用stopService()以及你正在得到什么错误。 稍微扩展你的问题,你可能会得到更多有用的回应。

你需要从你的活动中调用:

 stopService(new Intent(SummaryActivity.this, SocketService.class)); 

将“SummaryActivity”替换为您停止服务的Activity类的名称。

确保您在尝试停止所有绑定活动之前解除绑定。 正如Android文档所解释的,您无法停止当前绑定到某个活动的服务。

作为设计提示:通常在运行的Service中调用stopSelf() ,而不是直接使用stopService() 。 你可以在你的AIDL接口中添加一个shutdown()方法,它允许一个Activity请求一个stopSelf()被调用。 这封装了停止逻辑,并让您有机会在服务停止时控制服务的状态,类似于您将如何处理Thread

例如:

 public MyService extends IntentService { private boolean shutdown = false; public void doSomeLengthyTask() { // This can finish, and the Service will not shutdown before // getResult() is called... ... } public Result getResult() { Result result = processResult(); // We only stop the service when we're ready if (shutdown) { stopSelf(); } return result; } // This method is exposed via the AIDL interface public void shutdown() { shutdown = true; } } 

这是特别相关的,因为你的意图名字暗示你可能正在处理网络套接字。 在服务停止之前,您需要确保已经正确关闭了套接字连接。

只需在summaryActivity中调用stopService即可

开始服务:

 // Java Intent SocketServiceIntent = new Intent(this, SocketService.class); SocketServiceIntent.putExtra("MessageParcelable", mp); startService(SocketServiceIntent); //Kotlin startService(Intent(this, SocketService::class.java)) 

停止任何活动的服务:

 //Java stopService(new Intent(this, SocketService.class)) //Kotlin stopService(Intent(this, SocketService::class.java))