哦,这是我的问题.我有一个服务类,我设法创建媒体播放器,以便在后台播放音乐.这是代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我点击HOME或BACK按钮时出现问题.它仍然播放音乐.有谁知道如何解决这个问题?
以下是代码如何在课堂上调用此服务,我想播放音乐;
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
Run Code Online (Sandbox Code Playgroud)
Jon*_*ong 25
如果您只想为您的应用程序播放背景音乐,请在从您的app /使用AsyncTask类启动的线程中播放它以便为您完成.
服务的概念是在后台运行; 通过背景,通常意味着您的应用UI 不可见.是的,它可以像你一样使用(如果你记得停止它),但它不正确,它消耗你不应该使用的资源.
如果要在活动的背景上执行任务,请使用AsyncTask.
顺便说一句,onStart已弃用.当您使用服务时,请实施onStartCommand.
更新:
我认为这段代码对你有用.添加此类(包含在您的活动类中).
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,为了控制音乐,请保存您的BackgroundSound对象,而不是匿名创建它.将其声明为您活动中的字段:
BackgroundSound mBackgroundSound = new BackgroundSound();
Run Code Online (Sandbox Code Playgroud)
在您的活动的onResume方法上,启动它:
public void onResume() {
super.onResume();
mBackgroundSound.execute(null);
}
Run Code Online (Sandbox Code Playgroud)
在你的活动的onPause方法上,停止它:
public void onPause() {
super.onPause();
mBackgroundSound.cancel(true);
}
Run Code Online (Sandbox Code Playgroud)
这会奏效.