我有 App.java ,可在final Gson gson = new GsonBuilder()
.registerTypeAdapter(Wrapper.class, getWrapperDeserializer(new Gson()))
.create();
final String json = "{\"a\": {\"b\":\"c\"}}";
final Wrapper outerWrapper = (Wrapper) gson.fromJson(json, Wrapper.class);
final Wrapper innerWrapper = outerWrapper.wrapperBy("a");
out.println(innerWrapper.valueBy("b"));
中启动2项服务。
我有一个 MainActivity ,在MainActivity的onCreate()
方法中,我需要停止这两项服务。
我该怎么办?由于这个MainActivity没有启动这两项服务,是否可以停止它?
答案 0 :(得分:1)
您可以直接使用stopService()
:
stopService(new Intent(MainActivity.this, YourService.class));
但正如seanhodges中https://stackoverflow.com/a/9665584/4758255所说,
通常最好从正在运行的Service中调用stopSelf() 而不是直接使用stopService()。您可以在AIDL接口中添加shutdown()方法,这允许Activity请求调用stopSelf()。
使用AIDL界面,您可以使用EventBus。
这样的事情:
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;
}
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
// This method receive the Event for stopping the service
@Subscribe
public void onMessageEvent(StopServiceEvent event) {
shutdown = true;
}
}
StopServiceEvent 是一个简单的类:
public class StopServiceEvent {
}
您只需发送活动即可停止 MainActivity 中的服务:
EventBus.getDefault().post(new StopServiceEvent());