use*_*776 5 java service android android-intent
如何在其他活动中停止我的服务?
我在summaryActivity中启动了该服务
SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);
startService(SocketServiceIntent);
Run Code Online (Sandbox Code Playgroud)
从我的summaryActivity开始我的statusActivity
Intent intent = new Intent(SummaryActivity.this,
StatusActivity.class);
intent.putExtra("MessageParcelable", mp);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道如何将我的Statusactivity提供给SocketServiceIntent.
你应该致电Activity(ContextWrapper)#stopService:
stopService(new Intent(SummaryActivity.this, SocketService.class));
Run Code Online (Sandbox Code Playgroud)
您还没有解释您目前如何尝试使用 stopService() 以及您遇到了什么错误。稍微扩展您的问题,您可能会得到更多有用的答复。
您需要从您的活动中调用它:
stopService(new Intent(SummaryActivity.this, SocketService.class));
Run Code Online (Sandbox Code Playgroud)
将“SummaryActivity”替换为您停止服务的活动类的名称。
在尝试停止它之前,请确保您已将服务从所有绑定活动中解除绑定。正如Android 文档所解释的,您无法停止当前绑定到活动的服务。
作为设计提示:stopSelf()从正在运行的服务内部调用通常比stopService()直接使用更好。您可以shutdown()在 AIDL 接口中添加一个方法,该方法允许 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这尤其重要,因为您的意图名称表明您可能正在处理网络套接字。您需要确保在服务停止之前正确关闭了套接字连接。