【问题标题】:How to pause the service when the home button is pressed and resume the service when the program is resume?如何在按下主页按钮时暂停服务,在程序恢复时恢复服务?
【发布时间】:2015-02-24 16:24:46
【问题描述】:
public class BackgroundMusicService extends Service 
{
   int currentPos;
   /** indicates how to behave if the service is killed */
   int mStartMode;
   /** interface for clients that bind */
   IBinder mBinder;     
   /** indicates whether onRebind should be used */
   boolean mAllowRebind;

   MediaPlayer player;

   @Override
   public void onCreate() {
       super.onCreate();
       player = MediaPlayer.create(this, R.raw.tornado);
       player.setLooping(true); // Set looping
       player.setVolume(100,100);

   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
       player.seekTo(currentPos);
       player.start();
       return 1;
   }

   @Override
   public IBinder onBind(Intent intent) {
      return mBinder;
   }

   @Override
   public boolean onUnbind(Intent intent) {
      return mAllowRebind;
   }

   @Override
   public void onRebind(Intent intent) {

   }

   public void onPause()
   {
       player.pause();
   }

   @Override
   public void onDestroy() {
       player.stop();
       currentPos = player.getCurrentPosition();
   }
}

这是播放背景音乐的服务,如何在按下home键时暂停服务,在程序恢复时恢复服务?这是我的 MainActivity:

public class MainActivity extends ActionBarActivity
{
    int request_code = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(getBaseContext(), BackgroundMusicService.class));
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        stopService(new Intent(getBaseContext(), BackgroundMusicService.class));
    }
}

我觉得需要用到onPause()onResume()函数,但是怎么用呢?它应该在服务类或活动类中使用?
还有一点需要考虑,我使用了多个意图,并确保当我更改为 2nd 或其他意图时,服务仍在运行,这意味着更改意图不会停止播放背景音乐...除非 home按钮被按下或退出程序(这个我已经完成了)。

【问题讨论】:

    标签: android android-service


    【解决方案1】:

    你有你的 onPause 和 onResume 方法。您通常不需要扩展 Application 类,而是在您的 Activity 中使用它(尤其是如果您的应用程序只有一个 Activity)。

    但是,为什么要启动和停止服务呢?为什么不只是暂停/取消暂停音乐?您可以发送暂停/取消暂停(甚至切换)音乐播放的意图。

    【讨论】:

    • 如何发送暂停/恢复音乐的意图?
    • 基本上,您将创建一个您的服务将注册的意图并处理该意图。查看此答案以获取更多信息,它拥有您需要的一切:stackoverflow.com/a/21619248/447842
    猜你喜欢
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多