好了,这是我的问题。我有一个服务类,其中我成功地创建了媒体播放器,以便始终在后台播放音乐。下面是代码:
package com.test.brzoracunanje;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
player = MediaPlayer.create(this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
protected void onNewIntent() {
player.pause();
}
}但现在我在点击HOME或BACK按钮时遇到了问题。它还能播放音乐。有人知道如何解决这个问题吗?
这是我如何在我想要播放音乐的类上调用这个服务的代码;
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);发布于 2011-10-28 19:57:43
如果你只想为你的应用程序播放背景音乐,那么在你的应用程序启动的线程中播放它/使用AsyncTask类来为你做这件事。
服务的概念是在后台运行;在后台,其含义通常是当您的应用程序UI为NOT VISIBLE时。诚然,它可以像你一样使用(如果你记得停止它),但它就是不正确,而且它消耗了你不应该使用的资源。
如果要在activity的后台执行任务,请使用AsyncTask。
顺便说一句,onStart已被弃用。当您使用服务时,请实现onStartCommand。
更新:
我认为这段代码将为您工作。添加这个类(包含在您的activity类中)。
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(1.0f, 1.0f);
player.start();
return null;
}
}现在,为了控制音乐,保存你的BackgroundSound对象,而不是匿名创建它。在您的活动中将其声明为字段:
BackgroundSound mBackgroundSound = new BackgroundSound();在您的活动的onResume方法上,启动它:
public void onResume() {
super.onResume();
mBackgroundSound.execute(null);
}在你的活动的onPause方法上,停止它:
public void onPause() {
super.onPause();
mBackgroundSound.cancel(true);
}这将会起作用。
发布于 2016-03-30 01:30:08
AsyncTasks只适用于非常短的剪辑,但如果它是一个音乐文件,你将面临如下问题:
这里有几行来自安卓开发者页面关于AsyncTasks的内容
理想情况下,
AsyncTasks应该用于较短的操作(最多几秒钟)。如果您需要长时间保持线程运行,强烈建议您使用java.util.concurrent包提供的各种API,如Executor、ThreadPoolExecutor和FutureTask。
因此,目前我正在寻找其他选项,并在找到解决方案后更新答案。
发布于 2011-10-28 19:51:40
当然,你的服务是在后台运行的,当它进入后台时,你必须从你的活动中手动停止它。
https://stackoverflow.com/questions/7928803
复制相似问题