【问题标题】:How To stop Background service when i close app i want to stop background music当我关闭应用程序时如何停止后台服务我想停止背景音乐
【发布时间】:2017-01-27 06:22:24
【问题描述】:

我的 android 应用程序中有后台服务,我从 Splash_activity onCreate() 方法启动服务并且它工作正常。但是当用户按下 home_activity 后按时我如何停止服务。因为当前当用户按下主页按钮然后应用程序关闭但背景音乐不断播放。我无法停止背景音乐。下面是我的启动服务代码 -

Intent svc = new Intent(this, BackgroundSoundServi.class);
startService(svc);

我想在 home_activity 后按按钮中停止背景音乐,因为我在启动活动中启动服务,当用户返回多个(根据用户需要)时间时,它进入家庭活动,然后关闭应用程序。我已经尝试过onPause()onStop()onBackpress() 和 stackoverflow 所有其他解决方案,还阅读了关闭服务的服务完整流程,但我无法解决问题,请指导我,我是 android 新手。

我还想设置开/关背景音乐选项我应该怎么做...?以及它是如何工作的。

【问题讨论】:

  • 尝试代码并判断是否有效?

标签: android android-service


【解决方案1】:

在您的home_activity 内部使用:

@Override
protected void onPause() {
    super.onPause();
    stopService(new Intent(home_activity.this,BackgroundSoundService.class));      
}

【讨论】:

  • Error:(124, 15) 错误:没有找到适合 Intent(Activity_Latest,Class) 的构造函数 Intent.Intent(String,Uri) 不适用(参数不匹配;Activity_Latest 不能转换为String)构造函数Intent.Intent(Context,Class>)不适用(参数不匹配;Activity_Latest不能转换为Context)
  • 添加正确的类名。这个
  • public void onPause() { super.onPause(); stopService(new Intent(Activity_Latest.this,BackgroundSoundService.class)); } BackgroundSoundService 是正确的类名 & Activity_Latest Service 是我的家庭活动
  • 您是否将其用作生命周期,而不是像 oncreate 这样的任何地方?
  • 是的。我正在使用外部 oncreate()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
相关资源
最近更新 更多